-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
  • 330,695
  • 80
  • 606
  • 657
Pyd
  • 5,668
  • 14
  • 46
  • 94

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
  • 14,712
  • 2
  • 33
  • 62
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
  • 131,677
  • 37
  • 301
  • 358