List Comprehension in Python

  • Post category:List

List comprehension is a concise way to create new lists from existing lists or other iterable objects in Python. Here are two examples:

Example 1:

numbers = [1, 2, 3, 4, 5]
squared_numbers = [x ** 2 for x in numbers]
print(f"Squared numbers: {squared_numbers}")

Output:

Squared numbers: [1, 4, 9, 16, 25]

Example 2:

names = ['Alice', 'Bob', 'Charlie']
uppercase_names = [name.upper() for name in names]
print(f"Uppercase names: {uppercase_names}")

Output:

Uppercase names: [‘ALICE’, ‘BOB’, ‘CHARLIE’]