-2

I've a list like this:

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

I wish to convert it to:

a=['b','c']

How do I do that?

Mithil Bhoras
  • 337
  • 5
  • 14

2 Answers2

3

You can use list comprehension (which is pretty fast in this case):

print [item for sublist in a for item in sublist]

Demo:

>>> l = ['b', ['c']]
>>> [item for sublist in l for item in sublist]
['b', 'c']

Note:

This will only work if the list has strings of length 1, as @RemcoGerlich commented.

Edit:

If the string has more than 1 character, you can use the following approach (note that compiler was deprecated in Python 3):

from compiler.ast import flatten    
print flatten(a)
Christian Tapia
  • 33,620
  • 7
  • 56
  • 73
0

An alternative approach using map:

reduce((lambda arr,x: arr + list(x)),a,[])

Example:

>>> a=['b',['c']]
>>> a = reduce((lambda arr,x: arr + list(x)),a,[])
>>> a
['b', 'c']
Raul Guiu
  • 2,374
  • 22
  • 37