Python Forum
modifying the origin of an iterator
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
modifying the origin of an iterator
#1
suppose i call iter() to create an iterator from a large list. if i subsequently modify that list, will that impact that iterator or is an iterator from iter() completely independent, such as by making a copy of the origin object passed in the call to iter()?

based on readings of the python documentation, it appears that the data object is used, but it does not indicate if that is a copy or not.
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#2
There is no copy. Why would python build a copy if it doesn't know that you need one?
>>> L = list(range(10))
>>> it = iter(L)
>>> next(it)
0
>>> del L[1]
>>> next(it)
2
Reply
#3
i can't think of a reason. but that (my inability to think of a reason) doesn't mean that a developer didn't think of one.

it would be helpful if documentation indicated that the origin object should not be modified for the duration of using the iterator.
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#4
It does!
documentation Wrote:Code that modifies a collection while iterating over that same collection can be tricky to get right. Instead, it is usually more straight-forward to loop over a copy of the collection or to create a new collection
Reply
#5
i don't see this in the reference document. a tutorial is not organized for looking stuff up, so i don't go there.
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  testing if an iterator is empty Skaperen 9 8,982 Feb-25-2022, 02:31 AM
Last Post: Skaperen
  multiplying an iterator Skaperen 9 3,257 Oct-12-2021, 07:07 PM
Last Post: Skaperen
  iterating an iterator by one step Skaperen 0 1,580 Feb-09-2021, 08:38 PM
Last Post: Skaperen

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020