I really am at a loss as to why this list comprehension is generating different output to what I thought the equivalent with nested for loops. Can anyone shed any insight?
The list comprehension:
[(n ** 5, m ** 3) for n in range(3) for m in range(5) if m % 2 == 0]
Results in the following:
[(0, 0), (0, 8), (0, 64), (1, 0), (1, 8), (1, 64), (32, 0), (32, 8), (32, 64)]
However, what I believe is the equivalent nested For loop:
L = []
for n in range(3):
for m in range(5):
if m % 2 == 0:
n = n**5
m = m**3
vals = (n,m)
L.append(vals)
L
Results in the following:
[(0, 0),
(0, 8),
(0, 64),
(1, 0),
(1, 8),
(1, 64),
(32, 0),
(33554432, 8),
(42535295865117307932921825928971026432, 64)]
Why is there a difference in the output between the two?
Your nested loop is not equivalent to the list comprehension, because you have altered n
in the inner loop:
n = n**5
For any value other than 0
or 1
this increases n
exponentially. So for the last iteration of the outer loop n = 2
is set, but then you assign 2 ** 5 = 32
to n
, and then 32 ** 5 = 33554432
.
Use a different name:
L = []
for n in range(3):
for m in range(5):
if m % 2 == 0:
n_power_5 = n**5
m_power_3 = m**3
vals = (n_power_5, m_power_3)
L.append(vals)
or just don't use intermediate variables at all:
for n in range(3):
for m in range(5):
if m % 2 == 0:
L.append((n**5, m**3))
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.