List comprehensions provide a concise and elegant way to create lists. They allow you to build new lists by applying an expression to each item in an existing iterable, optionally with a condition.
🔹 1. What is a List Comprehension?
A single line of code to create a new list based on an existing sequence.
Syntax:
new_list = [expression for item in iterable if condition]
The
if condition part is optional.🔹 2. Basic List Comprehension
Creating a new list by transforming each item from an existing list or range.
Example (Squares):
numbers = [1, 2, 3, 4, 5]
squares = [num × num for num in numbers]
print(squares)
Output:
[1, 4, 9, 16, 25]Example (Uppercase names):
names = ["alice", "bob", "charlie"]
upper_names = [name.upper() for name in names]
print(upper_names)
Output:
['ALICE', 'BOB', 'CHARLIE']🔹 3. List Comprehension with Condition (
if)You can include an
if clause to filter items, only including those that satisfy the condition.Example (Even numbers):
all_numbers = range(10) # 0 to 9
even_numbers = [num for num in all_numbers if num % 2 == 0]
print(even_numbers)
Output:
[0, 2, 4, 6, 8]Example (Words starting with 'a'):
words = ["apple", "banana", "apricot", "cherry"]
a_words = [word for word in words if word.startswith('a')]
print(a_words)
Output:
['apple', 'apricot']🔹 4. List Comprehension with
if-else (Conditional Expression)You can use an
if-else expression within the expression part to choose a value based on a condition.Syntax:
new_list = [expression_if_true if condition else expression_if_false for item in iterable]
Example:python
nums = [1, 2, 3, 4]
status = ["Even" if n % 2 == 0 else "Odd" for n in nums]
print(status)
Output:
['Odd', 'Even', 'Odd', 'Even']🎯 Today's Goal
✔️ Understand the structure of list comprehensions
✔️ Create new lists from existing iterables
✔️ Filter items using
if conditions✔️ Use
if-else for conditional value assignment