简体   繁体   中英

Trouble with assigning new values to the elements of an iterator using for loop in python

i have a problem with assigning new values to the elements of an iterator using for loop. let's say we have this list:

 some_2d_list = [['mean', 'really', 'is', 'jean'], ['world', 'my', 'rocks', 'python']]
why does this code work and change the elements of the original list(reversing the elements which themselves are lists):

 for items in some_2d_list: items = items.reverse()

but this one does not(we will have to use indexes to apply changes in this case):

 for items in some_2d_list: items = ["some new list"]
I was expecting this result with the latter code:

 some_2d_list = [["some new list"], ["some new list"]]

list.reverse reverses in-place and returns None, so

for items in some_2d_list:
    items = items.reverse()

reverses the existing list which is still in some_2d_list and assigns None to items .

When you enter the code block in for items in some_2d_list , items is a reference to the object still in some_2d_list . Anything that modifies the existing list, affects some_2d_list also. for example

>>> some_2d_list = [['mean', 'really', 'is', 'jean'],
...  ['world', 'my', 'rocks', 'python']]
>>> 
>>> for items in some_2d_list:
...     items.append('foo')
...     del items[1]
... 
>>> some_2d_list
[['mean', 'is', 'jean', 'foo'], ['world', 'rocks', 'python', 'foo']]

Augmented operations like "+=" are ambiguous. Depending on how any given type is implemented, it can update in place or create new objects. They work for lists

>>> some_2d_list = [['mean', 'really', 'is', 'jean'],
...  ['world', 'my', 'rocks', 'python']]
>>> 
>>> for items in some_2d_list:
...     items += ['bar']
... 
>>> some_2d_list
[['mean', 'really', 'is', 'jean', 'bar'], ['world', 'my', 'rocks', 'python', 'bar']]

but not for tuples

>>> some_2d_list = [('mean', 'really', 'is', 'jean'), ('world', 'my', 'rocks', 'python')]
>>> for items in some_2d_list:
...     items += ('baz',)
... 
>>> some_2d_list
[('mean', 'really', 'is', 'jean'), ('world', 'my', 'rocks', 'python')]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM