6

Is the following safe?

x = [1, 2, 3, 4]
x = [y+5 for y in x]

Does the list comprehension evaluate first, creating a new list, and then assign that new list to x? I was told once that changing a list while iterating over it is an unsafe operation.

1
  • Changing a list while iterating is not the same thing as iterating and assigning the result.
    – Matt Ball
    Apr 16, 2013 at 3:36

2 Answers 2

6

You aren't changing the list while iterating over it, you are creating a completely new list and then once it has been evaluated, you are binding it to the name x so everything is safe.

3

Yep, it's safe.

As you hinted, the right-hand side is evaluated first, and then its result (an entirely new list) is assigned to the name x. You're right that it's unsafe to change a list while iterating over it, but that's not happening in your code sample, so no worries.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.