70

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

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

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

congusbongus
  • 13,359
  • 7
  • 71
  • 99
  • I know I can do it the long way by using nested loops, but I was wondering if there's a one-liner to do the same thing. – congusbongus Feb 11 '13 at 07:33
  • 1
    Another easy and fast way is: >> lists = [['hello'], ['world', 'foo', 'bar']] ################### >>combinedLists = lists[0] + lists[1] – tairen Oct 07 '18 at 14:47

2 Answers2

138
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))
Nicolas
  • 5,583
  • 1
  • 25
  • 37
  • 4
    While the first choice looks nicer in my opinion. Using itertools is MUCH faster. This answer is great. – Inbar Rose Feb 11 '13 at 07:40
  • 3
    The first one looks nice. But its kind a hard for me to wrap my head around what variable goes where. – Aidis Mar 18 '20 at 18:15
  • I was using old-school lazy looping over 90,000 entries in a DF. It was taking forever. I switch to this and it was instant! I knew it was magically faster, but that was just silly. – broepke Apr 22 '21 at 00:39
  • 2
    @Aidis for you or anyone else that also gets confused: the best way to remember is that from the `for`, the order of expressions is the same as a normal, nested for-loop. – Griffin Jul 27 '21 at 09:50
8
from itertools import chain

combined = [['hello'], ['world', 'foo', 'bar']]
single = [i for i in chain.from_iterable(combined)]
akira
  • 6,050
  • 29
  • 37