Skip to content Skip to sidebar Skip to footer

Python List Comprehensions

I am learning python3 list comprehensions. I understand how to format a list comprehension: [equation, for loop, if statement for filtering], but I cannot figure out how to condens

Solution 1:

Your algorithm is equivalent to multiplying by powers of 2:

x = 3res = [x * 2**i for i in range(10)]

# [3, 6, 12, 24, 48, 96, 192, 384, 768, 1536]

To see why this is the case, note you are multiplying your starting number by 2 in each iteration of your for loop:

x = 3
res = [x]
for _ in range(9):
    y = x + x
    x = y
    res.append(y)

print(res)

# [3, 6, 12, 24, 48, 96, 192, 384, 768, 1536]

As @timgeb mentions, you can't refer to elements of your list comprehension as you go along, as they are not available until the comprehension is complete.

Post a Comment for "Python List Comprehensions"