Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 793
Barry Rosenberg Avatar asked Apr 16 '13 03:04

Barry Rosenberg


2 Answers

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.

like image 69
jamylak Avatar answered Oct 02 '22 06:10

jamylak


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.

like image 33
ron rothman Avatar answered Oct 02 '22 07:10

ron rothman