-1

I have this list:

list1 = [['a', 'b', 'c', 'd']]

The way I found to convert to one list:

list1 = [['a', 'b', 'c', 'd']]

result = []
for i in range(len(list1)):
    for j in range(len(list1[i])):
        result.append(list1[i][j])

print result

and result is:

['a', 'b', 'c', 'd']

Is there any other way to do this ??

dslackw
  • 83
  • 1
  • 7
  • 1
    possible duplicate of [Flattening a shallow list in Python](http://stackoverflow.com/questions/406121/flattening-a-shallow-list-in-python) – Lily Chung Aug 01 '14 at 21:44

4 Answers4

3

Just index the list at 0:

result = list1[0]

Demo:

>>> list1 = [['a', 'b', 'c', 'd']]
>>> result = list1[0]
>>> result
['a', 'b', 'c', 'd']
>>>

For more than one sublist, you can use itertools.chain.from_iterable:

>>> from itertools import chain
>>> list1 = [['a', 'b', 'c', 'd'], ['w', 'x', 'y', 'z']]
>>> list(chain.from_iterable(list1))
['a', 'b', 'c', 'd', 'w', 'x', 'y', 'z']
>>>
3

If you just have one item, obviously list1[0] will work.

Otherwise in the general case there have been similar questions, e.g. Making a flat list out of list of lists in Python

This gave several including including

sum(list1, [])
Community
  • 1
  • 1
doctorlove
  • 18,872
  • 2
  • 46
  • 62
1

You can concatenate lists together directly if you have several of them:

list1 = [['a', 'b', 'c', 'd'], ['e', 'f', 'g', 'h']]

result = []
for sublist in list1:
    result += sublist

print result

If it's just a single nested list, iCodez has a faster answer.

TheSoundDefense
  • 6,753
  • 1
  • 30
  • 42
1

You can do that or use a list comprehension. Both do the same thing, but this is more in the style of python and looks prettier (and works for list of lists), its also called flattening a list:

result = [item for sublist in l for item in sublist]

This will turn

[[1,2],[3,4]]

into

[1,2,3,4]

and

[[1,2,3,4]]

to

[1,2,3,4]
piergiaj
  • 629
  • 3
  • 9
  • for list of list of list (and more irregular lists), there are a bunch of methods here: http://stackoverflow.com/questions/2158395/flatten-an-irregular-list-of-lists-in-python – piergiaj Aug 01 '14 at 21:46