16. Filtering and transforming Data with List Comprehensions

Quiz: 0/6

List comprehensions are a concise way to create new lists by applying an expression to each item in an existing list or iterable. They allow you to transform data (modify it) and filter data (select specific items) in a single line of code. This makes your code cleaner and more efficient.

What is a List comprehension?

A list comprehension is a compact way to generate lists. It uses the following structure:

new_list = [expression for item in iterable]
  • expression: This is what you want to do with each item (e.g., modify it).
  • item: The current item in the iteration.
  • iterable: The list (or any other iterable like a tuple or string) you're going through.

You can also filter items by adding an if condition:

new_list = [expression for item in iterable if condition]

Why use List comprehensions?

  • Concise: It lets you write code in a single line instead of using loops.
  • Efficient: It can be faster than using a loop for simple tasks.
  • Readable: Once you understand the syntax, list comprehensions are easy to read.

Transforming Data with List comprehensions

Transforming data means modifying each item in a list based on some logic. With list comprehensions, you can easily perform operations on each item.

Example: Squaring numbers in a list

Let’s say you have a list of numbers, and you want to square each number.

numbers = [1, 2, 3, 4, 5]
squared_numbers = [x ** 2 for x in numbers]
print(squared_numbers)  # Output: [1, 4, 9, 16, 25]

In this example:

  • x ** 2 is the transformation (squaring the number).
  • for x in numbers iterates over each number in the list.

Filtering Data with List comprehensions

Filtering means selecting only the items that meet a certain condition.

Example: Selecting even numbers from a list

Let's say you want to keep only the even numbers in a list:

numbers = [1, 2, 3, 4, 5]
even_numbers = [x for x in numbers if x % 2 == 0]
print(even_numbers)  # Output: [2, 4]

Here:

  • The if x % 2 == 0 part is the condition. It checks if the number is even.
  • Only numbers that satisfy this condition will be included in the new list.

Combining transformation and filtering

You can also combine both filtering and transforming in a single list comprehension. This is useful when you want to apply a transformation to the filtered items.

Example: Squaring only the even numbers

Let’s square only the even numbers in the list:

numbers = [1, 2, 3, 4, 5]
squared_even_numbers = [x ** 2 for x in numbers if x % 2 == 0]
print(squared_even_numbers)  # Output: [4, 16]

Here:

  • The list comprehension filters out the odd numbers if x % 2 == 0.
  • Then, it squares the remaining even numbers x ** 2.

Additional examples

Here are more examples of how you can use list comprehensions for transforming and filtering data:

Transforming strings to uppercase:

words = ["hello", "world", "python"]
uppercase_words = [word.upper() for word in words]
print(uppercase_words)  # Output: ['HELLO', 'WORLD', 'PYTHON']

Filtering strings with more than 5 characters:

words = ["hello", "world", "python", "code"]
long_words = [word for word in words if len(word) > 5]
print(long_words)  # Output: ['python']

Combining transformation and filtering:

words = ["hello", "world", "python", "code"]
uppercase_long_words = [word.upper() for word in words if len(word) > 5]
print(uppercase_long_words)  # Output: ['PYTHON']

Best practices and tips

  • Keep it simple: List comprehensions are powerful, but don't overcomplicate them. If the logic becomes too complex, it's better to use a regular for loop for clarity.
  • Readability: If the list comprehension has multiple conditions or transformations, consider breaking it into multiple steps for readability.
  • Use for simple tasks: List comprehensions are best suited for tasks that involve simple transformations or filtering.

Summary

  • Transformation: Modify each item in the list using an expression.
  • Filtering: Select items that meet a specific condition.
  • Combining: Apply both filtering and transformation in one line.
  • Concise and readable: List comprehensions make your code more compact and often easier to understand.

Hands-On Practise

Exercise: Processing a List of student grades

You are given a list of student grades, and your task is to apply a series of transformations and filters using list comprehensions.

  1. Transform the grades to percentages. Each grade in the list is out of 100, but we will convert them to percentages by dividing each grade by 100. For example, a grade of 80 becomes 0.8 (which is 80% in decimal form).

  2. Filter out the students who scored less than 50%. You need to exclude the students whose percentage is below 50%.

  3. For the students who passed, increase their grade by 10%. After filtering the passing students (those who scored 50% or more), increase their grade by 10% (e.g., 0.8 becomes 0.88).

  4. Return the final list of passing students' updated grades in descending order.

Step-by-step instructions:

Input data: A list of grades (out of 100).

grades = [45, 78, 55, 90, 68, 23, 85, 64, 49]

Steps to complete:

  1. Transform grades to percentages.

    • Each grade should be divided by 100.
  2. Filter out students with less than 50%.

    • Only keep the students whose percentage is greater than or equal to 0.5.
  3. Increase the grade of passing students by 10%.

    • For each passing student, multiply their grade by 1.10 (which represents a 10% increase).
  4. Return the updated list sorted in descending order.

    • Sort the passing students' updated grades in descending order.

Bonus (optional challenge):

Modify the exercise to also calculate the average grade of the passing students and print it along with the sorted updated grades.

Output:

Quizzes: 0/6

Question 1:

What does the following list comprehension do: [x ** 2 for x in numbers]?

  • It adds 2 to each element in the list.
  • It squares each element in the list.
  • It filters out even numbers from the list.
  • It returns a list with numbers as strings.

Question 2:

Which of the following list comprehensions filters out odd numbers from the list?

  • [x for x in numbers if x % 2 != 0]
  • [x for x in numbers if x % 2 == 0]
  • [x for x in numbers]
  • [x ** 2 for x in numbers]

Question 3:

What does this combined list comprehension do: [x ** 2 for x in numbers if x % 2 == 0]?

  • It squares all numbers in the list.
  • It squares only even numbers in the list.
  • It squares only odd numbers in the list.
  • It filters out numbers greater than 5.

Question 4:

Which of the following is the correct way to transform all strings in a list to uppercase using list comprehension?

  • [word.lower() for word in words]
  • [word.upper() for word in words]
  • [word.capitalize() for word in words]
  • [word.split() for word in words]

Question 5:

What is the result of the following list comprehension: [word for word in words if len(word) > 5]?

  • It selects all words with 5 or fewer characters.
  • It selects all words with more than 5 characters.
  • It selects only the longest word in the list.
  • It reverses the order of the words in the list.

Question 6:

What is the best way to use list comprehension for filtering and transforming data at the same time?

  • Use a simple 'for' loop.
  • Use a list comprehension with an 'if' condition and a transformation in the expression.
  • Use a dictionary comprehension.
  • Use the map() function.

Feedback

Share your thoughts about this lesson

Discussion

Please log in to create a discussion.
Previous lessonUnderstanding nested structuresNext lessonFile Handling