6
Lesson 6
Using Functions in list comprehensions
List comprehensions are not just for simple calculations; you can also use functions within them to process data. This makes them even more powerful and flexible. Let’s break this down into simple, digestible steps.
A function is like a mini-program that does a specific task. For example:
What are functions?
A function is like a mini-program that does a specific task. For example:
len() gives the length of a string or list.str.upper() converts a string to uppercase.
Functions can be used in a list comprehension to transform or filter data.
Basic example: Transforming with a Function
Let’s say you have a list of words and want to convert them all to uppercase.
Without list comprehension:
words = ["apple", "banana", "cherry"] uppercase_words = [] for word in words: uppercase_words.append(word.upper()) # Call the upper() function print(uppercase_words) # Output: ['APPLE', 'BANANA', 'CHERRY']
With list comprehension:
words = ["apple", "banana", "cherry"] uppercase_words = [word.upper() for word in words] # Apply the function in-line print(uppercase_words) # Output: ['APPLE', 'BANANA', 'CHERRY']
How it works:
- The
word.upper() function is applied to eachword in the list. - The results are collected in a new list.
Using custom Functions
You can also use your own functions in a list comprehension.
Example: Square numbers using a Function
Define a function to calculate the square of a number:
def square(num): return num * num
Now, use it in a list comprehension:
numbers = [1, 2, 3, 4] squared_numbers = [square(num) for num in numbers] # Call the square() function print(squared_numbers) # Output: [1, 4, 9, 16]
Combining Functions and conditions
You can combine function calls with conditions to create more advanced list comprehensions.
Example: Square Only Even Numbers
def square(num): return num * num numbers = [1, 2, 3, 4, 5, 6] squared_evens = [square(num) for num in numbers if num % 2 == 0] print(squared_evens) # Output: [4, 16, 36]
How it works:
1. The
2. The
Multiple Functions
You can even chain multiple functions together.
Example: Clean and format Strings
Let’s clean up a list of strings by removing spaces and converting them to uppercase.
def clean_string(s): return s.strip() # Removes extra spaces words = [" apple ", " banana", "cherry "] cleaned_words = [clean_string(word).upper() for word in words] print(cleaned_words) # Output: ['APPLE', 'BANANA', 'CHERRY']
Real-Life use case: Filtering and transforming
Imagine you have a list of numbers, and you want to:
1. Keep only positive numbers.
2. Calculate their square roots.
import math numbers = [-9, 16, 25, -4, 36] positive_roots = [math.sqrt(num) for num in numbers if num > 0] print(positive_roots) # Output: [4.0, 5.0, 6.0]
How it works:
if num > 0 filters out the negative numbers.math.sqrt(num) calculates the square root of the remaining numbers.
Why use Functions in list comprehensions?
- Readability: Combines logic into a single, compact line.
- Efficiency: Reduces the need for extra loops or temporary variables.
- Flexibility: Works seamlessly with Python’s built-in or custom functions.
Tips
1. Start by writing out your logic with regular loops before converting to a list comprehension.
2. Keep your functions simple and focused on one task.
3. Test the function separately to ensure it works correctly before using it in a list comprehension.