[Tutor] How is the return statement working in this function?
Steven D'Aprano
steve at pearwood.info
Fri Apr 6 03:07:49 CEST 2012
Greg Christian wrote:
> I am just wondering if anyone can explain how the return statement in this
> function is working (the code is from activestate.com)? Where does x come
> from – it is not initialized anywhere else and then just appears in the
> return statement. Any help would be appreciated.
> return [2]+[x for x in s if x]
It's called a list comprehension, and is like a one-liner specialist for loop.
[x for x in s if x] builds a list using x as the loop variable. So the above
line can be considered as the equivalent of this:
result = []
for x in s:
if x:
result.append(x)
return [2] + result
--
Steven
More information about the Tutor
mailing list