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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With