Menu
Coddy logo textTech

Filtering

Lesson 3 of 9 in Coddy's Python List Comprehension course.

Let's assume you are given list of words, and you filter only the ones containing the character 'a',

words = ['pony', 'confine', 'utter', 'decrease', 'entertain']
filteres_words = []
for word in words:
	if 'a' in word:
    	filteres_words.append(word)

print(filteres_words)  # ['decrease', 'entertain']

Using list comprehension it can be done in one line,

words = ['pony', 'confine', 'utter', 'decrease', 'entertain']
filteres_words = [word for word in words if 'a' in word]

print(filteres_words)  # ['decrease', 'entertain']

This kind of operation is called filtering - selecting elements from an existing list that meet a certain condition and generating a new list containing only those elements.

Here is the full syntax,

lst = [expression for item in iterable if condition]

If the condition is True the item will be added to the new list.

lst will hold a new list resulted from the list comprehension operation.

challenge icon

Challenge

Easy

Given a list of number nums, calculate a new list where only the even numbers exists.

Store the new list in a variable named even_nums.

Try it yourself

nums = eval(input())  # Don't change this line

All lessons in Python List Comprehension