1

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

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

 op:
    ['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

op:
[<generator object <genexpr> at 0x2996cd0>]
1
  • 1
    if argument is iterable and you want to add all elements from said iterable, you are looking for list.extend method. list.append adds argument to list, in your case iterable (generator expression) itself. Commented May 5, 2016 at 12:08

1 Answer 1

5

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.