0

I have following list of lists, as a result after tokenizing:

[['Who', 'are', 'you', '?'],
 ['I', 'do', 'not', 'know', 'who', 'you', 'are'],
 ['What', 'is', 'your', 'name', '?']]

Now I would like to have a list containing the "simple" elements, e.g.:

['Who','are','you','?','I','do','not','know','who'...]

I have already tried everything I could possibly think of, using (nested) for loops, (nested) while loops... I either get the list ['Who','Who','Who',...] (and so on) or I get "list index out of range".

Can somebody please help me out? Thank you!

tobias_k
  • 81,265
  • 12
  • 120
  • 179
thesisstudent
  • 119
  • 1
  • 2
  • 12
  • In other words, you want to flatten the list of lists? See [this related question](http://stackoverflow.com/questions/2158395/flatten-an-irregular-list-of-lists-in-python), or in your simpler case, just `sum(lst, [])` – tobias_k Feb 24 '15 at 09:33
  • Possible duplicate of [flatten an (irregular) list of lists in Python](http://stackoverflow.com/questions/2158395/flatten-an-irregular-list-of-lists-in-python). – JNevens Feb 24 '15 at 09:35
  • possible duplicate of [python nested list comprehension](http://stackoverflow.com/questions/18072759/python-nested-list-comprehension) – Aprillion Feb 24 '15 at 09:35

4 Answers4

1

you can try this

Python >=2.6, use itertools.chain.from_iterable() which doesn't require unpacking the list:

>>> import itertools
>>> list2d = [["who", "are", "you", "?"]....]
>>> merged = list(itertools.chain.from_iterable(list2d))
Rajarshi Das
  • 11,778
  • 6
  • 46
  • 74
0

You can just use the extend function in python

In [1]: a= [['Who', 'are', 'you', '?'], ['I', 'do', 'not', 'know', 'who', 'you', 'are'], ['What', 'is', 'your', 'name', '?']]
In [2]: b = []
In [3]: for list_ in a:
    b.extend(list_)
   ...:     

In [4]: b
Out[4]: ['Who','are','you','?','I','do', ...]
Greg
  • 5,422
  • 1
  • 27
  • 32
0

Do you want to merge the list?

flat_list = []
for list_item in nested_list:
    flat_list += list_item

>>flat_list
>>['Who', 'are', 'you', '?', 'I', 'do', 'not', 'know', 'who', 'you', 'are', 'What', 'is', 'your', 'name', '?']

A possible duplicate can be viewed here

Community
  • 1
  • 1
hlkstuv_23900
  • 864
  • 20
  • 34
0

just for the record when seeing other answers, a more pythonic way is to use a nested list comprehension, like this:

original_list = [[1], [2, 3]]
flat_list = [i for sublist in original_list for i in sublist]
Community
  • 1
  • 1
Aprillion
  • 21,510
  • 5
  • 55
  • 89