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.
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.
The extend() method adds the specified list elements (or any iterable) to the end of the current list.
Much simpler and cleaner with list comprehension:
[y for x in originalList for y in doSomething(x)]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With