for loop in a single statement with list append function

When i execute the below code, i get the right results:

for i in quorum:
 print lst

    ['val1', 'val2', 'val3']

but when i try to have the for loop along with list append function in single line, i don’t get the expected output (i.e the list elements as above).

what am i missing ? and why does it behave that way ?

lst.append(i.strip('l') for i in quorum)
print lst

[<generator object <genexpr> at 0x2996cd0>]


The expression in parens is a generator expression (genex). It is an iterable, but list.append() doesn’t iterate. Fortunately list.extend() does:

lst.extend(i.strip('l') for i in quorum)

Leave a Reply

Your email address will not be published. Required fields are marked *