Introduction:
Welcome to this short tutorial, where we will explore how to effectively use loops with lists in Python. Our journey begins with understanding the basics of iterating through a list of items. We will then delve into the power of List Comprehensions, a feature in Python that enables advanced looping techniques in a more concise and readable manner. This tutorial will also demonstrate how to incorporate conditional statements within these comprehensions to further enhance their functionality and versatility.
The best tool to iterate inside a list is using the for loop command, let’s see an example:
# Define a list of numbers
numbers = [1, 2, 3, 4, 5]
# Iterate over the list using a for loopfornumberin numbers:
print(number)
The for loop is set up with the syntax for number in numbers, where number is a temporary variable that takes on the value of each element in the list as the loop iterates. Inside the loop, the print(number) statement is executed for each element, resulting in each number being printed to the console.
List comprehensions provide a concise and readable way to create new lists by applying an expression to each item in an existing list (or any iterable). It’s a very Pythonic way to handle list transformations. In a list comprehension, you typically include a for loop and an optional if condition inside square brackets. Let’s see an example where we use a list comprehension to create a new list based on an existing list.
Suppose we have a list of numbers, and we want to create a new list that contains the square of each number in the original list. Here’s how we can do it using a list comprehension:
# Define a list of numbers
numbers = [1, 2, 3, 4, 5]
# Create a newlistof squares using a list comprehension
squares = [number ** 2fornumberin numbers]
# Print the newlist
print(squares)
In this code, squares = [number ** 2 for number in numbers] is the list comprehension. It iterates over each number in the numbers list and applies the expression number ** 2 (which computes the square of the number). The result is a new list, squares, which contains the squares of the original numbers.
The output will be:
[1, 4, 9, 16, 25]
List comprehensions can also include conditions. For example, if you want to create a list of squares only for the even numbers in the original list, you could modify the list comprehension like this:
# Create a newlistof squares for even numbers only
even_squares = [number ** 2fornumberin numbers ifnumber % 2 == 0]
# Print the newlist
print(even_squares)
Output:
[4, 16]
In this modified version, if number % 2 == 0 is a condition that filters the list to include only even numbers before squaring them.