Changing iterable variable during loop

2024/10/10 18:20:57

Let it be an iterable element in python. In what cases is a change of it inside a loop over it reflected? Or more straightforward: When does something like this work?

it = range(6)
for i in it:it.remove(i+1)print i

Leads to 0,2,4 being printed (showing the loop runs 3 times).

On the other hand does

it = range(6)
for i in it:it = it[:-2]print it

lead to the output:

[0,1,2,3]
[0,1]
[]
[]
[]
[],

showing the loop runs 6 times. I guess it has something to do with in-place operations or variable scope but cannot wrap my head around it 100% sure.

Clearification:

One example, that doesn't work:

it = range(6)
for i in it:it = it.remove(i+1)print it

leads to 'None' being printed and an Error (NoneType has no attribute 'remove') to be thrown.

Answer

When you iterate over a list you actually call list.__iter__(), which returns a listiterator object bound to the list, and then actually iterate over this listiterator. Technically, this:

itt = [1, 2, 3]
for i in itt:print i

is actually kind of syntactic sugar for:

itt = [1, 2, 3]
iterator = iter(itt)
while True:try:i  = it.next()except StopIteration:breakprint i

So at this point - within the loop -, rebinding itt doesn't impact the listiterator (which keeps it's own reference to the list), but mutating itt will obviously impact it (since both references point to the same list).

IOW it's the same old difference between rebinding and mutating... You'd get the same behaviour without the for loop:

# creates a `list` and binds it to name "a"
a = [1, 2, 3] 
# get the object bound to name "a" and binds it to name "b" too.
# at this point "a" and "b" both refer to the same `list` instance
b = a 
print id(a), id(b)
print a is b
# so if we mutate "a" - actually "mutate the object bound to name 'a'" - 
# we can see the effect using any name refering to this object:
a.append(42)
print b# now we rebind "a" - make it refer to another object
a = ["a", "b", "c"]
# at this point, "b" still refer to the first list, and
# "a" refers to the new ["a", "b", "c"] list
print id(a), id(b)
print a is b
# and of course if we now mutate "a", it won't reflect on "b"
a.pop()
print a
print b
https://en.xdnf.cn/q/69868.html

Related Q&A

Are CPython, IronPython, Jython scripts compatible with each other?

I am pretty sure that python scripts will work in all three, but I want to make sure. I have read here and there about editors that can write CPython, Jython, IronPython and I am hoping that I am look…

Python. Print mac address out of 6 byte string

I have mac address in 6 byte string. How would you print it in "human" readable format?Thanks

Cursors with postgres, where is the data stored and how many calls to the DB

Hi I am using psycopg2 for postgres access.I am trying to understand where "cursor" stores the returned rows. Does it store it in the database as a temporary table or is it on the clients en…

Django - How to allow only the owner of a new post to edit or delete the post?

I will be really grateful if anyone can help to resolve the issue below. I have the following Django project coding. The problem is: when the browser was given "/posts/remove/<post_id>/"…

Py4J has bigger overhead than Jython and JPype

After searching for an option to run Java code from Django application(python), I found out that Py4J is the best option for me. I tried Jython, JPype and Python subprocess and each of them have certai…

how to uninstall opencv-python package installed by using pip in anaconda?

I have tried to install OpenCV in anaconda. but when I use it, I figure out the instead of using OpenCV, the program using OpenCV-python and that why my program crashed. I type "conda uninstall op…

flask many to many join as done by prefetch_related from django

I have following Group and Contact model in flask with Sql Alchemy ORMgroup_contact = db.Table(group_contact,db.Column(group_id, db.Integer, db.ForeignKey(group.id)),db.Column(contact_id, db.Integer, d…

Django model inheritance - only want instances of parent class in a query

Lets say I have 2 models, one being the parent of another. How can I query all Places that arent restaurants in Django? Place.objects.all() would include all restaurants right? I want to exclude the …

Perfom python unit tests via a web interface

Is it possible to perform unittest tests via a web interface...and if so how?EDIT: For now I want the results...for the tests I want them to be automated...possibly every time I make a change to the …

Limit on number of HDF5 Datasets

Using h5py to create a hdf5-file with many datasets, I encounter a massive Speed drop after ca. 2,88 mio datasets. What is the reason for this?I assume that the limit of the tree structure for the dat…