1

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.

Ray
  • 27
  • 5
  • 1
    If you'd like to know where to start, please look at [my answer here](http://stackoverflow.com/questions/6475314/python-for-in-loop-preceded-by-a-variable/37869704#37869704) – UltraInstinct Apr 21 '17 at 00:37

2 Answers2

1

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.

Rushy Panchal
  • 16,979
  • 16
  • 61
  • 94
  • 3
    You actually don't even need a list for the valid letters; the following suffices: `ahm_words = [w for w in words if w.lower()[0] in 'ahm']` – Jacob G. Apr 21 '17 at 00:32
  • 1
    Thanks you!! This was so helpful to see how you went about it. – Ray Apr 21 '17 at 01:57
1

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']
Paul Rooney
  • 20,879
  • 9
  • 40
  • 61
Claudio
  • 7,474
  • 3
  • 18
  • 48
  • Shouldn't it include `'Anyone'`? – Paul Rooney Apr 21 '17 at 00:41
  • @PaulRooney to include `Anyone` just extend `listOfChars` to `['a', 'h', 'm', 'A', 'H', 'M']` if you like. The purpose of the answer as I understand it is to give a start point towards list comprehensions, so it doesn't matter if the resulting list is "correct". If the OP has understood the list comprehension it will become easy to get it right oneself. – Claudio Apr 21 '17 at 00:47
  • Thank you for your help. – Ray Apr 21 '17 at 01:59