Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

join list of lists in python [duplicate]

Tags:

python

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 
like image 964
Kozyarchuk Avatar asked Apr 04 '09 04:04

Kozyarchuk


People also ask

How do I merge a list of lists in one list Python?

Use the sum() function to concatenate nested lists to a single list by passing an empty list as a second argument to it.

How do I combine multiple lists into one Python?

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.

How do you merge two lists without duplicates in Python?

Python merges two lists without duplicates could be accomplished by using a set. And use the + operator to merge it.

How do you flatten a list of lists?

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] .


1 Answers

import itertools a = [['a','b'], ['c']] print(list(itertools.chain.from_iterable(a))) 
like image 78
CTT Avatar answered Sep 22 '22 19:09

CTT