I have a list of lists
LL = [[1;2;3];[4;5;6];[7;8;9]]
And I would like it to look like this
LSimple= [1;2;3;4;5;6;7;8;9]
That's as simple as I can ask it, but maybe rewording helps. How can I parse this lists of lists and create a simple list from it?
There are a number of ways to flatten a list of lists in python. You can use a list comprehension, the itertools library, or simply loop through the list of lists adding each item to a separate list, etc. Let's see them in action through examples followed by a runtime assessment of each.
Flatten List of Lists Using itertools (chain()) This approach is ideal for transforming a 2-D list into a single flat list as it treats consecutive sequences as a single sequence by iterating through the iterable passed as the argument in a sequential manner.
📢 TLDR: Use + In almost all simple situations, using list1 + list2 is the way you want to concatenate lists. The edge cases below are better in some situations, but + is generally the best choice. All options covered work in Python 2.3, Python 2.7, and all versions of Python 31.
List.concat LL
Will do what you want. The X.concat family of functions concatenate any sequence of the collection X to a single X where X may be a List
, Array
, Seq
or even a String
with a given separator.
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