Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python list comprehension to join list of lists [duplicate]

Given lists = [['hello'], ['world', 'foo', 'bar']]

How do I transform that into a single list of strings?

combinedLists = ['hello', 'world', 'foo', 'bar']

like image 389
congusbongus Avatar asked Feb 11 '13 07:02

congusbongus


People also ask

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 combine lists within a list Python?

Concatenate Two Lists in Python In almost all simple situations, using list1 + list2 is the way you want to concatenate lists.


1 Answers

lists = [['hello'], ['world', 'foo', 'bar']] combined = [item for sublist in lists for item in sublist] 

Or:

import itertools  lists = [['hello'], ['world', 'foo', 'bar']] combined = list(itertools.chain.from_iterable(lists)) 
like image 108
Nicolas Avatar answered Oct 07 '22 01:10

Nicolas