Python: Adding element to list while iterating
Python: Adding element to list while iterating
--
Become part of the top 3% of the developers by applying to Toptal
https://topt.al/25cXVn
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzle Game 5 Looping
--
Chapters
00:00 Question
01:19 Accepted answer (Score 12)
01:49 Answer 2 (Score 60)
02:45 Answer 3 (Score 26)
03:13 Answer 4 (Score 10)
05:26 Thank you
--
Full question
https://stackoverflow.com/questions/3752...
Answer 2 links:
[http://docs.python.org/tutorial/controlf...]: http://docs.python.org/tutorial/controlf...
Answer 3 links:
[stackoverflow question]: https://stackoverflow.com/questions/6260...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #iteration
#avk47
ANSWER 1
Score 65
Why don't you just do it the idiomatic C way? This ought to be bullet-proof, but it won't be fast. I'm pretty sure indexing into a list in Python walks the linked list, so this is a "Shlemiel the Painter" algorithm. But I tend not to worry about optimization until it becomes clear that a particular section of code is really a problem. First make it work; then worry about making it fast, if necessary.
If you want to iterate over all the elements:
i = 0
while i < len(some_list):
more_elements = do_something_with(some_list[i])
some_list.extend(more_elements)
i += 1
If you only want to iterate over the elements that were originally in the list:
i = 0
original_len = len(some_list)
while i < original_len:
more_elements = do_something_with(some_list[i])
some_list.extend(more_elements)
i += 1
ANSWER 2
Score 28
well, according to http://docs.python.org/tutorial/controlflow.html
It is not safe to modify the sequence being iterated over in the loop (this can only happen for mutable sequence types, such as lists). If you need to modify the list you are iterating over (for example, to duplicate selected items) you must iterate over a copy.
ACCEPTED ANSWER
Score 12
You could use the islice from itertools to create an iterator over a smaller portion of the list. Then you can append entries to the list without impacting the items you're iterating over:
islice(myarr, 0, len(myarr)-1)
Even better, you don't even have to iterate over all the elements. You can increment a step size.
ANSWER 4
Score 5
You can do this.
bonus_rows = []
for a in myarr:
if somecond(a):
bonus_rows.append(newObj())
myarr.extend( bonus_rows )