-1

I have a list like this,

 my_list = ["one two","three two"]

I want to convert it to,

 out_list=["one","two","three","two"]

I am getting the output by doing,

out_list=[item.split() for item in my_list]
out_list=sum(out_list,[])

I am looking for the easiest way to do the same in a single line, but I hope there is a simple way to do this in python, Thanks in advance!

cs95
  • 379,657
  • 97
  • 704
  • 746
Pyd
  • 6,017
  • 18
  • 52
  • 109

2 Answers2

5

A fun alternative to the obvious and superior in its generality answer by @Yarmash:

my_list = ["one two","three two"]
res = ' '.join(my_list).split()
print(res)  # -> ['one', 'two', 'three', 'two']

' '.join(my_list) creates a string that looks like this "one two three two" which is then split using the default delimiter (whitespace).

Ma0
  • 15,057
  • 4
  • 35
  • 65
1

You can do it with a single list comprehension:

>>> my_list = ["one two", "three two"]
>>> [y for x in my_list for y in x.split()]
['one', 'two', 'three', 'two']
Eugene Yarmash
  • 142,882
  • 41
  • 325
  • 378