Barry Rosenberg
Barry Rosenberg

Reputation: 278

Is it safe to assign list comprehension to the original list?

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.

Upvotes: 7

Views: 294

Answers (2)

ron rothman
ron rothman

Reputation: 18128

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.

Upvotes: 4

jamylak
jamylak

Reputation: 133544

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.

Upvotes: 7

Related Questions