Vishnukk
Vishnukk

Reputation: 564

Convert comma separated string to list items in Python

I have a list like the following:

my_list = ['google', 'microsoft,facebook']

and I need to convert this into:

my_list = ['google', 'microsoft', 'facebook']

I tried doing it this way:

new_list = [item.split(',') for item in my_list]
flat_list = [item for sublist in new_list for item in sublist]

but this method involves unnecessary additional variables and multiple for loops. Is there a way we can make this easier?

Upvotes: 0

Views: 164

Answers (5)

Linda Goba
Linda Goba

Reputation: 76

You can do this by converting to the list to string and back to list as follows:

my_list = ['google','microsoft,facebook']

newList = ','.join(my_list).split(',')

Output:

['google', 'microsoft', 'facebook']

Upvotes: 3

BoarGules
BoarGules

Reputation: 16942

If you insist on doing it in-place, then you can do

for i,e in enumerate(my_list):
    my_list[i:i+1] = e.split(",")

Upvotes: 1

cards
cards

Reputation: 4975

You can flat the list with sum(mylist, [])

l = ['google','microsoft,facebook']

ll = sum([s.split(',')  for s in l], [])

print(ll)

Output

['google', 'microsoft', 'facebook']

Upvotes: 0

user2390182
user2390182

Reputation: 73460

You can do this in one nested comprehension:

new_list = [x for item in my_list for x in item.split(',')]

Or use itertools.chain:

from itertools import chain

new_list = [*chain(*(item.split(',') for item in my_list))]
# or the more traditional
new_list = list(chain.from_iterable(item.split(',') for item in my_list))

And if you want to go all out with the functional utils:

from functools import partial

new_list = [*chain(*map(partial(str.split, sep=","), my_list))]

Upvotes: 1

balderman
balderman

Reputation: 23815

The below is simple enough (make en empty list and extend it)

my_list = ['google','microsoft,facebook']
new_list = []
for x in my_list:
  new_list.extend(x.split(','))
print(new_list)

output

['google', 'microsoft', 'facebook']

Upvotes: 4

Related Questions