-2

This piece of python code is an example of list comprehension

lst = [ x**2 for x in [x**2 for x in range(11)]]

# [0, 1, 16, 81, 256, 625, 1296, 2401, 4096, 6561, 10000]

How would this be written if it was not in list comprehension?

My understanding is that the list generated is the square of the square of each number in range(11). So I understand this is how to get the first part:

lst = []
for item in range(11):
    lst.append(item**2)
print(lst)

# [0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

But how can I get the second part?

bluesky
  • 153
  • 8
  • You've done the first half, which is the inner list. What is left is to handle the rest, which is `lst = [x**2 for x in lst]`. You do it the same way. – zvone Oct 31 '20 at 16:50
  • Related: [Understanding nested list comprehension](https://stackoverflow.com/questions/8049798/understanding-nested-list-comprehension) – wwii Oct 31 '20 at 16:54
  • If one of the answers solved your problem, could you please check this question as answered? Thank you – Oliver Hnat Oct 31 '20 at 17:06
  • But ... why to not `x**4`? – Olvin Roght Oct 31 '20 at 17:31

4 Answers4

2
lst = [ x**2 for x in [x**2 for x in range(11)]]

# equivalent to:
squares = []
squares2 = []
for x in range(11):
    squares.append(x**2)

for item in squares:
    squares2.append(item**2)
    
print(squares2)
print(squares2==lst)

output:

[0, 1, 16, 81, 256, 625, 1296, 2401, 4096, 6561, 10000]
True
Yossi Levi
  • 1,258
  • 1
  • 4
  • 7
1

Do the loop twice

lst = []
for item in range(11):
    lst.append(item**2)
i = 0
for item in lst:
    lst[i] = (item**2)
    i = i + 1
print(lst)
Oliver Hnat
  • 797
  • 4
  • 19
1

The comprehension is equivalent to

lst = []
for item in range(11):
    lst.append((item**2)**2)

after which you can

print(lst)

to observe

[0, 1, 16, 81, 256, 625, 1296, 2401, 4096, 6561, 10000]
Captain Trojan
  • 2,800
  • 1
  • 11
  • 28
  • The comprehension has the same result as this, but it does it differently, by executing two loops... – zvone Oct 31 '20 at 16:51
  • @zvone Which is both inefficient and redundant c: – Captain Trojan Oct 31 '20 at 16:57
  • But the question is about what the comprehension is doing, not how to make it better. – zvone Oct 31 '20 at 17:11
  • @zvone "How would this be written if it was not in list comprehension?" in my books means: "Show me equivalent code that does not use list comprehension." OP's initial code clearly shows how the elements of range(11) are mapped to x1 and then to x2, which is exactly what my code does. – Captain Trojan Oct 31 '20 at 17:39
1

It is the same as:

lst = []
num_lst = []
for x in range(11):
    num_lst.append(x**2)
for x in num_lst:
    lst.append(x**2)
print(lst)

Output:

[0, 1, 16, 81, 256, 625, 1296, 2401, 4096, 6561, 10000]
Sushil
  • 5,440
  • 1
  • 8
  • 26