List comprehensions - Exercises
Now, let us practice list comprehensions.
Many thanks to the following people for contributing to these exercises: Joe Stacey, Oana Cocarascu
Ex1: Use list comprehension to print the number of words in a sentence that do not have a letter ‘a’ in
Ex2: Print the number of words in a sentence that start with a capital letter
Ex3: Use list comprehension to print a list of all the words in a sentence that have more than 5 characters
Ex4: Use list comprehension to return only the elements of list(range(40)) that divide by both 4 and 6
Ex5: Use list comprehension to write a program that takes a string as input, and:
- Removes . and , symbols
- And cuts out any words with a length of between 2 to 6 characters
- Returns the remaining string
Challenge questions
Ex6: Write a program that takes a list containing lists for each element, and instead produces a single list that combines together the elements from each indiviudal list.
- For example, the program would take
my_list = [[1, 2], [2, 3, 4], [4, 5]]
and would output[1, 2, 2, 3, 4, 4, 5]