How to use list comprehension in Python?
List comprehension is a concise and powerful way to create lists in Python. It allows you to create a new list by applying an expression to each item in an existing iterable.
List comprehension is a readable and efficient alternative to traditional loops when building lists.
numbers = [1, 2, 3, 4, 5]
squares = [num**2 for num in numbers]
Syntax
new_list = [expression for item in iterable if condition]
-
new_list
: The new list that will be created.expression
: The expression that is applied to each item in the iterable to create the new list.item
: A variable that represents each item in the iterable.iterable
: The original iterable (e.g., list, tuple, string) from which the new list is created.if condition
: (Optional) A condition that filters the items in the iterable. Only items that satisfy this condition will be included in the new list.
How to use list comprehension in Python
# Example 1: Creating a new list of squares of numbers using list comprehension
numbers = [1, 2, 3, 4, 5]
squares = [num**2 for num in numbers]
print("Squares:", squares) # Output: Squares: [1, 4, 9, 16, 25]
# Example 2: Creating a new list of even numbers from a given 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:", even_numbers) # Output: Even Numbers: [2, 4, 6, 8, 10]
# Example 3: Creating a new list of uppercase characters from a string
string = "hello world"
uppercase_chars = [char.upper() for char in string if char.isalpha()]
print("Uppercase Characters:", uppercase_chars)
# Output: Uppercase Characters: ['H', 'E', 'L', 'L', 'O', 'W', 'O', 'R', 'L', 'D']