Adding Conditions
Part of the Logic & Flow section of Coddy's Python journey — lesson 52 of 78.
List comprehensions become even more powerful when you add conditional logic. This allows you to create new lists based on existing lists, filtering and transforming elements based on specified conditions.
The syntax for adding a condition to a list comprehension is:
new_list = [expression for item in iterable if condition]Here's a breakdown of the syntax:
new_list: The new list that will be created.
expression: The value to be included innew_list. This can be a modified version ofitem.
for item in iterable: A loop that iterates over each element in theiterable(e.g., a list, tuple, or range).
item: The current element being processed in the loop.
if condition: A filter that determines whether the currentitemshould be included innew_list. Theexpressionis only evaluated if theconditionisTrue.
Here's an example:
numbers = [1, 2, 3, 4, 5, 6]
evens = [n for n in numbers if n % 2 == 0]
print(evens)
# Output: [2, 4, 6]In this example, the list comprehension creates a new list called evens by taking each element n from the numbers list and including it only if it is even (i.e., n % 2 == 0).
Challenge
EasyCreate a function named filter_and_square that takes a list of numbers numbers as an argument. The function should use a list comprehension to create a new list that includes the squares of only the positive numbers from the original list. The function should return the new list.
Cheat sheet
List comprehensions with conditional logic allow you to filter and transform elements based on specified conditions:
new_list = [expression for item in iterable if condition]expression: The value to be included in the new listfor item in iterable: Loop over each elementif condition: Filter that determines if the item should be included
Example - filtering even numbers:
numbers = [1, 2, 3, 4, 5, 6]
evens = [n for n in numbers if n % 2 == 0]
print(evens)
# Output: [2, 4, 6]Try it yourself
def filter_and_square(numbers):
# Write code hereThis lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Variables Exploration
ConstantsMultiple Variable AssignmentsSwapping VariablesPlaceholder VariablesRound NumbersList Casting4Contact Book Application
Display MenuAdd Contact7Sets Part 2
Mathematical Operations Part 1Mathematical Operations Part 2Recap - Treasure HuntSubsets and SupersetsIterating Over SetsRecap - Tournament Tracker10Basic List Comprehensions
The SyntaxCreating Simple ListsAdding ConditionsUsing Data AggregationRecap - House Of ListsRecap - Elements Of Freedom2Dictionaries Part 1
What is a Dictionary?Creating a DictionaryAccessing ValuesModifying DictionariesRecap - Recipe Manager5Advanced Decision Making
Ternary OperatorMembership ChecksIdentity ChecksIndentation ErrorsRecap - Vacation Filter8Student Records Manager
Project OverviewAdd Student11Advanced Functions
Returning Multiple ValuesLambda Functions Part 1Lambda Functions Part 2Recap Challenge - Lambda SortRecursive Functions Part 1Recursive Functions Part 2Recap - Sum Nested List14Higher-Order Functions
The Map FunctionThe Filter FunctionRecap - Email ValidatorRecap - Number Processor3Dictionaries Part 2
Dictionary MethodsNested DictionariesChecking for KeysLooping Through DictionariesRecap - Frequency Counter9Advanced Data Aggregation
Using SumFinding Minimum and MaximumSorting Data EfficientlyRecap - Dictionary Sorter