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
_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor

Reply via email to