I have the following piece of code:
[e for e in [sl] for sl in [1,[2,3],4,5]]
which I thought being equivalent (in terms of output) to:
[sl for sl in [1,[2,3],4,5]]
Yet, while the latter produces: [1,[2,3],4,5]
the former returns: [5, 5, 5, 5]
I think it must have something do with how nested for-statements
are evaluated.
I found a similar case here Weird behavior: Lambda inside list comprehension but since it uses an anonymous functions, the reason behind this behavior should be different.
Clearly, there's something I'm missing and I don't see.
Thank you for any clarification
UPDATE
As Patrick pointed out, the order of the two for
is wrong and shouldn't run unless sl
was defined before. I fooled myself here because I ran the examples in the interpreter and [sl for sl in [1,[2,3],4,5]]
was executed first leaving sl
set to the last value of the list in globals()
Now it would be great to understand how this is evaluated
[e for e in [sl] for sl in [1,[2,3],4,5]]
in order to produce [5, 5, 5, 5]
in output.