Nathan Brinda
Nathan Brinda

Reputation: 49

separating multiple words out of the same index

I have a list with multiple words per index, and i need to split the words into different indexes.

mylist = ['hell o', 'geg gg' etc...]

How do i turn the above list into.

newList = ['hell', 'o' , 'geg', 'gg']

Upvotes: 0

Views: 27

Answers (2)

jamylak
jamylak

Reputation: 133544

Another way of doing it

>>> from itertools import chain
>>> mylist = ['hell o', 'geg gg']
>>> list(chain.from_iterable(map(str.split, mylist)))
['hell', 'o', 'geg', 'gg']

Upvotes: 1

unutbu
unutbu

Reputation: 879451

You could use a list comprehension:

In [192]: mylist = ['hell o', 'geg gg']

In [193]: [part for item in mylist for part in item.split()]
Out[193]: ['hell', 'o', 'geg', 'gg']

[part for item in mylist for part in item.split()]

is equivalent to to the value assigned to result by

result = list()
for item in mylist:
    for part in item.split():
        result.append(part)

Upvotes: 1

Related Questions