Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use a list comprehension to extend a list in python? [duplicate]

I'm not experienced in Python, and I often write code that (simplified) looks like this:

accumulationList = []
for x in originalList:
    y = doSomething(x)
    accumulationList.append(y)
return accumulationList

Then after my test passes, I refactor to

return [doSomething(x) for x in originalList]

But suppose it turns out a little different, and my loop looks like this:

accumulationList = []
for x in originalList:
    y = doSomething(x)
    accumulationList.extend(y)
return accumulationList

where the doSomething list returns a list. What is the most Pythonic way to accomplish this? Obviously, the previous list comprehension would give a list of lists.

like image 386
Eric Wilson Avatar asked May 10 '11 08:05

Eric Wilson


People also ask

Can you use continue in list comprehension Python?

The concept of a break or a continue doesn't really make sense in the context of a map or a filter , so you cannot include them in a comprehension.

What is the list extend () method?

The extend() method adds the specified list elements (or any iterable) to the end of the current list.


1 Answers

Much simpler and cleaner with list comprehension:

[y for x in originalList for y in doSomething(x)]
like image 165
Shubham Chaudhary Avatar answered Sep 28 '22 05:09

Shubham Chaudhary