Python: List Comprehension

Study Guide

  • Complete the W3Schools lesson.

  • Watch the Socratica video on List Comprehension. (Duration: 8 minutes)

Feedback

  • Is there anything we can help with up to this point? Do you have something to suggest about this chapter? Let us know in the comments below.

3 replies on “Python: List Comprehension”

HI
I try the code many time but i don’t get the same answer :
squares = []
for i in range(1,10):
squares.append (i**2)
print(squares)

print(“separation”)

squares2 =[i**2 for i in range(1,10)]
print(squares2)
=================== answer ===========
[1]
[1, 4]
[1, 4, 9]
[1, 4, 9, 16]
[1, 4, 9, 16, 25]
[1, 4, 9, 16, 25, 36]
[1, 4, 9, 16, 25, 36, 49]
[1, 4, 9, 16, 25, 36, 49, 64]
[1, 4, 9, 16, 25, 36, 49, 64, 81]
separation
[1, 4, 9, 16, 25, 36, 49, 64, 81]
+++++++++++++++ YOUR HELP +++++++++
pleace help me .
I don’t know why it ‘s not the same

If you change the code to the following, you’ll get the same results. Study the change and try to understand the differences:

squares = []
for i in range(1,10):
squares.append (i**2)
print(squares) # <-- Move this out of the for loop print('separation') squares2 =[i**2 for i in range(1,10)] print(squares2)

Leave a Reply