Is the a short syntax for joining a list of lists into a single list( or iterator) in python?
For example I have a list as follows and I want to iterate over a,b and c.
x = [["a","b"], ["c"]]
The best I can come up with is as follows.
result = [] [ result.extend(el) for el in x] for el in result: print el
Use the sum() function to concatenate nested lists to a single list by passing an empty list as a second argument to it.
Concatenation is one of the easiest ways to combine list elements or strings while codding in Python. But while using the chains() method, import the itertools module using the import statement. Additionally, you can also use methods such as join() to concatenate two strings.
Python merges two lists without duplicates could be accomplished by using a set. And use the + operator to merge it.
Flattening a list of lists entails converting a 2D list into a 1D list by un-nesting each list item stored in the list of lists - i.e., converting [[1, 2, 3], [4, 5, 6], [7, 8, 9]] into [1, 2, 3, 4, 5, 6, 7, 8, 9] .
import itertools a = [['a','b'], ['c']] print(list(itertools.chain.from_iterable(a)))
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