Assigning a value to a slice element in Python

This is a simple question about how Python handles data and variables. I experimented a lot and Python basically figured out, except that it disables me:

[edit: I divided and rebuilt the examples for clarity]

Example 1:

>>> a = [[1], 2]
>>> a[0:1]
[[1]]
>>> a[0:1] = [[5]]
>>> a
[[5], 2] # The assignment worked.

Example 2:

>>> a = [[1], 2]
>>> a[0:1][0]
[1]
>>> a[0:1][0] = [5]
>>> a
[[1], 2] # No change?

Example 3:

>>> a = [[1], 2]
>>> a[0:1][0][0]
1
>>> a[0:1][0][0] = 5
>>> a
[[5], 2] # Why now?

Can someone explain to me what is going on here?

So far, the answers seem to claim to a[0:1]return a new list containing a link to the first element a. But I do not understand how this is explained in Example 1.

+5
source share
3 answers

a [0: 1] , [1], .

, [1], , .

- a [0: 1] , .

+7

- . .

,

>>> a = [[1], 2, 3]
>>> k = a[0:2]
>>> id(a)
4299352904
>>> id(k)
4299353552
>>> 

>>> id(a)
4299352904
>>> id(a[0:2])
4299352832

>>> k = 5
>>> 
>>> id(k)
4298182344
>>> a[0] = [1,2]
>>> a
[[1, 2], 2, 3]
>>> id(a)
4299352904
>>> 

[: ]

>>> a[0:1] = [[5]]

slice (delete + insert) . , .

+3

, :

  • a[i] = b = > a.__setitem__(i, b)
  • del a[i] = > a.__delitem__(i)
  • a[i] = > a.__getitem__(i)

a, b i , i , . :.

>>> class C(object):
...     def __setitem__(self, *a):
...             print a
... 
>>> C()[1] = 0
(1, 0)
>>> C()['foo'] = 0
('foo', 0)
>>> C()['foo':'bar'] = 0
(slice('foo', 'bar', None), 0)
>>> C()['foo':'bar',5] = 0
((slice('foo', 'bar', None), 5), 0)

, :

a[0:1][0][0] = 5

a.__getitem__(slice(0,1)).__getitem__(0).__setitem__(0, 5)

__getitem__ , __getitem__ , __setitem__.

, ,

a.__getitem__(slice(0,1)).__setitem__(0, 5)

, __setitem__ , .

+1

All Articles