Reputation: 517
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 condense three lines of code into a single equation for the 'equation' part.
I am taking a number and adding it to itself and then taking the result and adding it to itself and so on to create a sequence of numbers in the list.
I can accomplish this by declaring x = 1 and then looping the following:
y = x + x
x = y
Can anybody help me to turn this into a single-lined equation and if possible, resources that I might study to help me with this in the future?
Upvotes: 1
Views: 805
Reputation: 164693
Your algorithm is equivalent to multiplying by powers of 2:
x = 3
res = [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.
Upvotes: 3