pythonpython-assignment-expression

Can assignment expression create Fibonacci series using list comprehension?


With assignment expression, I thought I could try list comprehension to create Fibonacci. I first initialize a Fibonacci list of 5 elements f = [1,2,3,4,5] with the first two values being the seeds. The test run below shows the assignment expression works.

[y := f[n-1] + f[n-2] for n in range(2,6)] 
[3, 5, 7, 9]

But the real Fibonacci failed at f[n] where a red marker showed in Python shell.

[f[n] := f[n-1] + f[n-2] for n in range(2,6)] 

Is it because the f[n] is not a valid variable name?
Does that mean assignment expression might not help in list comprehension for Fibonacci?


Solution

  • Using [f[n] := ... results in SyntaxError: cannot use assignment expressions with subscript, so clearly this restriction prevents doing it that way. This is mentioned in PEP 572 in a section titled Differences between assignment expressions and assignment statements where is says