Reputation: 53
I am using Python my list is
str = ["Hello dude", "What is your name", "My name is Chetan"]
I want to separate each word in each sentence in the string and store it in new_list. new_list will be like
new_list = ["Hello", "dude", "What", "is", "your", "name", "My", "name",
"is", "Chetan"]
I tried with the code
for row in str:
new_list.append(row.split(" "))
Output:
[['Hello', 'dude'], ['What', 'is', 'your', 'name'], ['My', 'name', 'is',
'Chetan']]
which is list of list
Upvotes: 4
Views: 1388
Reputation: 6152
you have,
values = ["Hello dude", "What is your name", "My name is Chetan"]
then use this one liner
' '.join(values).split()
Upvotes: 2
Reputation: 24922
You could use itertools.chain
from itertools import chain
def split_list_of_words(list_):
return list(chain.from_iterable(map(str.split, list_)))
DEMO
input_ = [
"Hello dude",
"What is your name",
"My name is Chetan"
]
result = split_list_of_words(input_)
print(result)
#['Hello', 'dude', 'What', 'is', 'your', 'name', 'My', 'name', 'is', 'Chetan']
Upvotes: 3
Reputation: 1539
Try this:-
str = ["Hello dude", "What is your name", "My name is Chetan"]
ls = []
for i in str:
x = i.split()
ls +=x
print(ls)
Upvotes: 1
Reputation: 78780
You are almost there. All that's left to do is to un-nest your list.
final_result = [x for sublist in new_list for x in sublist]
Or without a list comprehension:
final_result = []
for sublist in new_list:
for x in sublist:
final_result.append(x)
Of course, all of this can be done in a single step without producing new_list
first explicitly. The other answers already covered that.
Upvotes: 1
Reputation: 7268
You can try:
>>> new_list=[]
>>> str = ["Hello dude", "What is your name", "My name is Chetan"]
>>> for row in str:
for data in row.split():
new_list.append(data)
>>> new_list
['Hello', 'dude', 'What', 'is', 'your', 'name', 'My', 'name', 'is', 'Chetan']
Upvotes: 0
Reputation: 82795
This should help. Instead of append use extend
or +=
str = ["Hello dude", "What is your name", "My name is Chetan"]
new_list = []
for row in str:
new_list += row.split(" ") #or new_list.extend(row.split(" "))
print new_list
Output:
['Hello', 'dude', 'What', 'is', 'your', 'name', 'My', 'name', 'is', 'Chetan']
Upvotes: 1