简体   繁体   中英

List comprehensions in Python “freezing” Jupyter notebook

When I run the code below in Jupyter notebook, my "kernel" freezes (I get an asterisk between the square brackets like so: [*]):

x = [1,2,3,4]
for num in x:
    x.append(num**2)

Why doesn't this code "append" the exponentiated numbers to the end of x?

The code below works and I understand why, but why doesn't the code above work:

x = [1,2,3,4]
out = []
for num in x:
    out.append(num**2)
print(out)

You are iterating over a list, and in every iteration you append a new element to the list, so the iteration is never going to end.

To see what's happening, change your code to this:

import time

x = [1,2,3,4]
for num in x:
    x.append(num**2)
    time.sleep(0.5)
    print(x)

If you know what you are doing, you can avoid this kind of "dynamic iteration" with the [:] trick:

x = [1,2,3,4]
for num in x[:]:
    x.append(num**2)

This way you are iterating over x[:] , not the growing x , in effect it's like you are iterating over a snapshot of x .

More concisely, you could use a list comprehension as follows:

x = [1,2,3,4]
x_squared = [elem**2 for elem in x]
x.extend(x_squared)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM