How can I use list comprehension to expand a list in python?

I have no experience 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 will reorganize

 return [doSomething(x) for x in originalList] 

But suppose this is a little different, and my loop looks like this:

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

where doSomething list returns a list. What is the most pythonic way to achieve this? Obviously, a previous understanding of the list gave a list of lists.

+8
python list-comprehension
source share
5 answers

Much easier and cleaner with list comprehension:

 [y for x in originalList for y in doSomething(x)] 
+4
source share

Do you mean something like this?

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

or shorter code (but not optimal):

 return sum((doSomething(x) for x in originalList), []) 

or the same thing:

 return sum(map(doSomething, originalList), []) 

Thanks to @eyquem for a hint (if using Python 2.x):

 import itertools as it return sum(it.imap(doSomething, originalList), []) 
+4
source share

The in-place Python add operator ( += , available as iadd in the operator module) is equivalent to .extend for the list. Combine it with reduce to get what you want.

 import operator reduce(operator.iadd, (doSomething(x) for x in originalList) , accumulation_list) 
+2
source share

I think the answers related to add or iadd are executed in quadratic time, which is probably not very good. I would try:

 from itertools import chain accumulation_list = list(chain.from_iterable(doSomething(x) for x in originalList)) 
+2
source share

I do not think there is a special syntax for this case. But you can make the for loop shorter:

 accumulationList += doSomething(x) 

If you insist, you can use functional programming to smooth the list:

 result = reduce(lambda a,b: a+b, [[i,i*2] for i in range(3)]) 

But I would not call it pythonic, I think it is harder to read than the for loop.

0
source share

All Articles