Ray
Ray

Reputation: 27

Python List Comprehension how-to

Newbie to Python...trying to take sentence = "Anyone who has never made a mistake has never tried" and:

  1. Convert sentence to list
  2. Use list comprehension to create a new list containing word beginning with letters 'A, H and M'.

Able to convert sentence to list using string.split()

string = "Anyone who has never made a mistake has never tried anything new"
string.split()
['Anyone', 'who', 'has', 'never', 'made', 'a', 'mistake', 'has', 'never', 'tried', 'anything', 'new']

Need help with the list comprehension. No clue where to start.

Upvotes: 1

Views: 87

Answers (2)

user7711283
user7711283

Reputation:

Python syntax helps usually to understand what the code does. Hope you get the idea how to filter items from a list using a given if condition:

# string = "Anyone who has never made a mistake has never tried anything new"
# string.split()
listOfWords = ['Anyone', 'who', 'has', 'never', 'made', 'a', 'mistake', 'has', 'never', 'tried', 'anything', 'new']
listOfChars = ['a', 'h', 'm']

wordsBeginningWithAHM = [word for word in listOfWords if word[0] in listOfChars]
print( wordsBeginningWithAHM )

gives:

['has', 'made', 'a', 'mistake', 'has', 'anything']

Upvotes: 1

Rushy Panchal
Rushy Panchal

Reputation: 17532

You have a list of word and you want to get the words that start with 'A', 'H', or 'M'. So, check that condition in the list comprehension:

string = "Anyone who has never made a mistake has never tried anything new"
words = string.split()
ahm_words = [w for w in words if w.lower()[0] in 'ahm']

Your result is in ahm_words.

See: https://docs.python.org/2/tutorial/datastructures.html#list-comprehensions.

Upvotes: 1

Related Questions