for loop in a single statement with list append function Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of for loop in a single statement with list append function without wasting too much if your time.

The question is published on by Tutorial Guruji team.

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>]

Answer

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)
We are here to answer your question about for loop in a single statement with list append function - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji