10 Python List Comprehension Practice Exercises That Will Make You A Hiring Manager's Dream
How can a python newbie can stand out in a sea of competition? Show your list comprehension
As a Software Quality Assurance Engineer, I use python as one tool in my test automation tool chest. List comprehension is one of the python techniques that not only adds flair to your code, it also saves cpu cycles and is considered ‘Pythonic’.
What is list comprehension?
The list comprehension syntax is somewhat of a compressed ‘for’ loop.
Classic ‘for’ loop
Given a list of numbers, remove all odd numbers from the list:
numbers = [3,5,45,97,32,22,10,19,39,43]
result = []
for number in numbers:
if number % 2 == 0:
result.append(number)
print(result)
The list comprehension way
result = [number for number in numbers if number % 2 == 0]
print(result)
So glorious, so pretty, so pythonic ;)
List comprehension syntax
The trickiest part of learning list comprehension for me was really understanding the syntax. The best method of explaining IMO is from Tutorial – Python List Comprehension With Examples
A traditional for loop:
Translated to list comprehension:
And another great visual
Examples
Given a list of numbers, remove floats (numbers with decimals)
original_list = [2,3.75,.04,59.354,6,7.7777,8,9]
only_ints = [number for number in original_list if type(number) == int]
print(only_ints)
Practice
I needed practice, so I used this list. Each challenge below links to a solution gist.
- Find all of the numbers from 1-1000 that are divisible by 7
- Find all of the numbers from 1-1000 that have a 3 in them
- Count the number of spaces in a string
- Create a list of all the consonants in the string “Yellow Yaks like yelling and yawning and yesturday they yodled while eating yuky yams”
- Get the index and the value as a tuple for items in the list “hi”, 4, 8.99, ‘apple’, (‘t,b’,’n’). Result would look like (index, value), (index, value)
- Find the common numbers in two lists (without using a tuple or set) list_a = 1, 2, 3, 4, list_b = 2, 3, 4, 5
- Get only the numbers in a sentence like ‘In 1984 there were 13 instances of a protest with over 1000 people attending’
- Given numbers = range(20), produce a list containing the word ‘even’ if a number in the numbers is even, and the word ‘odd’ if the number is odd. Result would look like ‘odd’,’odd’, ‘even’
- Produce a list of tuples consisting of only the matching numbers in these lists list_a = 1, 2, 3,4,5,6,7,8,9, list_b = 2, 7, 1, 12. Result would look like (4,4), (12,12)
- Find all of the words in a string that are less than 4 letters
- Use a nested list comprehension to find all of the numbers from 1-1000 that are divisible by any single digit besides 1 (2-9)