abc
abc

Reputation: 113

Python List comprehension (convert sentence to words)

I am new to python and have a simple doubt.

I am trying list comprehension.

I am trying to add words from a string into a list. But unable to do so. What am I doing wrong?

sentence = "there is nothing much in this"

wordList = sentence.split(" ") #normal in built function
print wordList

wordList = [ x for x in sentence if x!=" "] #using list comprehension
print wordList

Upvotes: 2

Views: 2842

Answers (1)

James Mills
James Mills

Reputation: 19030

The following:

wordList = [ x for x in sentence if x!=" "] #using list comprehension
print wordList

will not work as you expect.

List Comphrehsnios in Python are basically a short-hand form of writing normal for-loops.

The above could be written as:

wordList = []
for x in sentence:
    if x != "":
        wordList.append(x)

print wordList

Do you see why this wouldn't work?

This would in effect iterate over all the characters in the string sentence.

Anything that you can do with a for-loop you can do with a list comprehension.

Example:

xs = []
for i in range(10):
    if i % 2 == 0:
        xs.append(i)

is equivalent to:

xs = [i for i in range(10) if i % 2 == 0]

Upvotes: 2

Related Questions