Chetan Tamboli
Chetan Tamboli

Reputation: 53

extract each word from list of strings

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

Answers (7)

Haseeb A
Haseeb A

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

user459872
user459872

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

Narendra
Narendra

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

timgeb
timgeb

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

Yuankun
Yuankun

Reputation: 7803

new_list = [x for y in str for x in y.split(" ")]

Upvotes: 1

Harsha Biyani
Harsha Biyani

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

Rakesh
Rakesh

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

Related Questions