I have a bunch of lists I want to append to a single list that is sort of the \"main\" list in a program I\'m trying to write. Is there a way to do this in one line of code
If you prefer a slightly more functional approach, you could try:
import functools as f
x = [1, 2, 3]
y = [4, 5, 6]
z = [7, 8, 9]
x = f.reduce(lambda x, y: x+y, [y, z], x)
This will enable you to concatenate any number of lists onto list x
.
If you would just like to concatenate any number of lists together (i.e. not onto some base list), you can simplify to:
import functools as f
from operator import add
big_list = f.reduce(add, list_of_lists)
Take note that our BFDL has his reservations with regard to lambdas, reduce, and friends: https://www.artima.com/weblogs/viewpost.jsp?thread=98196
To complete this answer, you can read more about reduce in the documentation: https://docs.python.org/3/library/functools.html#functools.reduce
I quote: "Apply function of two arguments cumulatively to the items of sequence, from left to right, so as to reduce the sequence to a single value."
P.S. Using sum()
as described in https://stackoverflow.com/a/41752487/532513 is super compact, it does seem to work with lists, and is really fast (see https://stackoverflow.com/a/33277438/532513 ) but help(sum)
in Python 3.6 has the following to say:
This function is intended specifically for use with numeric values and may reject non-numeric types.
Although this is slightly worrying, I will probably keep it as my first option for concatenating lists.