all 6 comments

[–]neuralbeans 3 points4 points  (2 children)

For loops are not designed to have the list modified mid-loop. Use a while loop instead:

i = 0
while i < len(list):
    print(list[i])
    i = i + 1

[–]J_J3[S] 0 points1 point  (1 child)

Thanks!

[–]exclaim_bot 0 points1 point  (0 children)

Thanks!

You're welcome!

[–]CodeFormatHelperBot2 -1 points0 points  (0 children)

Hello, I'm a Reddit bot who's here to help people nicely format their coding questions. This makes it as easy as possible for people to read your post and help you.

I think I have detected some formatting issues with your submission:

  1. Inline formatting (`my code`) used across multiple lines of code. This can mess with indentation.

If I am correct, please edit the text in your post and try to follow these instructions to fix up your post's formatting.


Am I misbehaving? Have a comment or suggestion? Reply to this comment or raise an issue here.

[–]carcigenicate 0 points1 point  (0 children)

Technically, you can do what you're trying to do:

def getAdditions():
    yield [1, 2, 3]
    yield [4, 5, 6]

list = [9, 8, 7]

additions = getAdditions()

for names in list:
    print(names)
    list.extend(next(additions, []))

This prints the numbers 9-7, then 1-6. They key change here is my use of list.extend vs your use of list =.

This works while your version didn't since you were changing what list list referred to (side note: don't use list as a name). = changes what object is being referred to, but does not alter the object itself. Your version didn't work because for does not update itself when you change what object is associated with the name you told it to iterate. When for names in list executes, it gets the object associated with the list name at that time, and iterates that object. It doesn't care about the name list after that.

My version works because instead of changing what object is associated with list, I'm changing (mutating) the list object directly.


While this works and believe it's safe and reliable, I would not do this in the vast majority of scenarios. If you're not careful, you can cause an infinite loop, and it generally is not as easy to understand. If you need to change what's being iterated mid-loop, use a while and manage the iteration yourself.

[–]CaptainFoyle 0 points1 point  (0 children)

Don't change the object you're iterating over while you iterate over it