Sangamesh
Sangamesh

Reputation: 545

List of list to string

I have a list of list for example :

sample = [['a'],['b']]

I want this list to be converted to a string list like

sample = ['a','b']

I have used lists before but this seems to be bothering me!! Thanks in advance

Upvotes: 0

Views: 62

Answers (3)

Fredrik Pihl
Fredrik Pihl

Reputation: 45662

Try this:

In [5]: sample = [['a'],['b']]

In [6]: [item for sublist in sample for item in sublist]
Out[6]: ['a', 'b']

or

In [10]: from itertools import chain

In [11]: list(chain.from_iterable(sample))
Out[11]: ['a', 'b']

Upvotes: 1

theharshest
theharshest

Reputation: 7867

Simple for loops would be enough -

>>> s = [['a'],['b']]
>>> t = []
>>> for a in s:
        for b in a:
            t.append(b)


>>> t
['a', 'b']

Upvotes: 0

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798746

You haven't covered all the cases, but:

[''.join(x) for x in sample]

Upvotes: 0

Related Questions