Conditional Statements in Collections in Python
Overview
This lesson focuses on how to use conditional statements within collections in Python. Conditional statements, such as if
, elif
, and else
, play a critical role in filtering, searching, and decision-making operations within collections like lists, dictionaries, sets, and tuples.
Introduction
Conditional statements allow you to execute certain pieces of code depending on whether a specified condition is true or false. When working with collections, these conditions can be used to check for the presence of elements, compare values, or even filter data based on specific criteria.
Using Conditionals in List Comprehensions
List comprehensions offer a concise way to create lists. You can include conditional statements within a list comprehension to filter items.
- Syntax:
[expression for item in iterable if condition]
- Example:
# Creating a new list with even numbers from an existing list
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = [num for num in numbers if num % 2 == 0]
print(even_numbers)
Filtering Data in Dictionaries
You can use conditional statements to filter data in dictionaries based on specific criteria.
- Example:
# Filtering a dictionary by value
people = {'Alice': 25, 'Bob': 30, 'Charlie': 35, 'Diana': 28}
adults = {k: v for k, v in people.items() if v >= 30}
print(adults)
Conditional Statements in Sets
Sets can be filtered using conditional statements to create new sets based on specific conditions.
- Example:
# Creating a set that contains only odd numbers from a range
odd_numbers = {num for num in range(1, 11) if num % 2 != 0}
print(odd_numbers)
Searching in Tuples with Conditional Statements
While tuples are immutable, you can still iterate over them and apply conditional checks to find elements or derive new collections.
- Example:
# Finding elements greater than a certain value
tup = (1, 2, 3, 4, 5)
greater_than_three = tuple(num for num in tup if num > 3)
print(greater_than_three)
Using Conditional in Loops
When iterating over collections, you can use conditional statements within loops to perform operations on certain elements.
- Example:
# Printing only the positive numbers from a list
numbers = [1, -2, 3, -4, 5]
for num in numbers:
if num > 0:
print(num)