Solution to Python Basics Exercises

The exercises:

  1. EX. Using the list of words you produced by splitting 'new_string', create a new list that contains only the words whose last letter is "y".

  2. EX. Create a new list that contains the first letter of each word.

  3. EX. Create a new list that contains only words longer than two letters.

We can do all of this using built-in Python functions: arithmetic, string manipulation, and list comprehension.

First, the sentence 'new_string'. We can split 'new_string' into a list of words using the .split() function


In [ ]:
# copying 'new_string' from the tutorial on Wednesday

new_string = "It seems very strange that one must turn back, \
and be transported to the very beginnings of history, \
in order to arrive at an understanding of humanity as it is at present."

#creat a new variable containing a list of words using the .split() function
new_string_list = new_string.split() 
#print the new list
new_string_list

(1) EX. Using the list of words you produced by splitting 'new_string', create a new list that contains only the words whose last letter is "y"

We can combine list comprehension and the string manipulation function .endswith(), both of which we learned about on Wednesday, to create a new list the keeps only the elements from the original list that end with the character 'y'.


In [ ]:
word_list_y = [word for word in new_string_list if word.endswith('y')]
#print the new list
word_list_y

(2) EX. Create a new list that contains the first letter of each word.

We can again use list comprehension, combined with string splicing, to produce a new list that contain only the first letter of each word. Remember in Python counting starts at 0.


In [ ]:
word_list_firstletter = [word[0] for word in new_string_list]
#print our new list
word_list_firstletter

(3) EX. Create a new list that contains only words longer than two letters.

We can, again, use list comprehension, the 'len' function, and the algorithm function greater than, or '>', to filter and keep words longer than two letters. Note that '>' is strictly greater than. If we wanted to include words with 2 letters we would need to use greater than or equal to, or '>='.

Syntax is important here, so refer to the tutorial from Wednesday to remind yourself of the syntax. Use copy and paste to avoid errors in typing.


In [ ]:
word_list_long = [n for n in new_string_list if len(n)>2]
#print new list
word_list_long