Using Data Aggregation
Part of the Logic & Flow section of Coddy's Python journey — lesson 53 of 78.
List comprehensions provide a concise way to create new lists based on existing iterables. You can integrate data aggregation functions like sum(), min(), and max() directly within list comprehensions to perform calculations on the elements of the new list as it's being created.
Calculating the Sum of Squares:
numbers = [1, 2, 3, 4, 5]
sum_of_squares = sum([n * n for n in numbers])
print(sum_of_squares)
# Output: 55In this example, the list comprehension [n * n for n in numbers] creates a list of squares, and the sum() function calculates the sum of these squares.
Finding the Minimum of Transformed Values:
numbers = [-3, -1, 0, 1, 3]
min_absolute = min([abs(n) for n in numbers])
print(min_absolute)
# Output: 0Here, the list comprehension [abs(n) for n in numbers] creates a list of absolute values, and the min() function finds the minimum value in this list.
Finding the Maximum of Filtered Values:
numbers = [1, 2, 3, 4, 5, 6]
max_even = max([n for n in numbers if n % 2 == 0])
print(max_even)
# Output: 6In this example, the list comprehension [n for n in numbers if n % 2 == 0] creates a list of even numbers, and the max() function finds the maximum value in this list.
Challenge
EasyWrite a function sum_positive_evens that takes a list of numbers as input. Use a list comprehension to filter positive even numbers, then use sum() to calculate their total. Return the result.
Example input:
numbers = [-10, -5, 0, 2, 4, 7, 10, 12]Example output:
28Cheat sheet
List comprehensions can be combined with aggregation functions like sum(), min(), and max() to perform calculations on transformed or filtered data.
Calculate sum of squares:
numbers = [1, 2, 3, 4, 5]
sum_of_squares = sum([n * n for n in numbers])
# Output: 55Find minimum of transformed values:
numbers = [-3, -1, 0, 1, 3]
min_absolute = min([abs(n) for n in numbers])
# Output: 0Find maximum of filtered values:
numbers = [1, 2, 3, 4, 5, 6]
max_even = max([n for n in numbers if n % 2 == 0])
# Output: 6Try it yourself
def sum_positive_evens(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