I have several lists, stored in a list, itself created in a loop of unknown number of iterations, and I need to concatenate them all. Example:
lists = [range(i) for i in range(1,5)]
lists
Out[1]: [[0], [0, 1], [0, 1, 2], [0, 1, 2, 3]]
So, now I want to turn them into a single, flat list. I can do this by just adding them:
biglist = lists[0] + lists[1] + lists[2] + lists[3]
...but that gets boring very quickly. I could write a for
loop which iterates over the inner lists:
biglist = []
for smallist in lists:
biglist += smallist
biglist
Out[2]: [0, 0, 1, 0, 1, 2, 0, 1, 2, 3]
This works but requires three lines of code and handling intermediate results, so it cannot work inline and gets in the way of preferring functional code.
But since all I need is to add some lists to each other, and there's already a builtin function for that in Python, it stands to reason I could just use sum(lists)
-- however:
sum(lists)
Traceback (most recent call last):
File "D:\program_files\Anaconda\envs\SPINE_dev\lib\site-packages\IPython\core\interactiveshell.py", line 2878, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-12-827ffc5ab7d2>", line 1, in <module>
sum(lists)
TypeError: unsupported operand type(s) for +: 'int' and 'list'
What's the issue? Should this not work? I went looking for an answer and only found this trick, which works, but without explanation:
sum(lists, [])
Out[3]: [0, 0, 1, 0, 1, 2, 0, 1, 2, 3]
Note that the original hint was to use list(sum(lists, []))
, but it seems to work just fine without using list()
, which looks much better, too.
So, the question: Why do I need to supply an empty list? Secondary question: Why would someone recommend wrapping that statement in a type conversion, and are there scenarios (or Python versions) where that would be necessary?
I'm using Python 2.7.10