List comprehension

# Using a loop
squares_loop = []
for x in range(10):
    squares_loop.append(x**2)

# Using a list comprehension
squares_comprehension = [x**2 for x in range(10)]

print("Squares with loop:", squares_loop)
print("Squares with comprehension:", squares_comprehension)
Squares with loop: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
Squares with comprehension: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
# List of even squares using a loop
even_squares_loop = []
for x in range(10):
    if x % 2 == 0:
        even_squares_loop.append(x**2)

# List of even squares using a list comprehension
even_squares_comprehension = [x**2 for x in range(10) if x % 2 == 0]

print("Even squares with loop:", even_squares_loop)
print("Even squares with comprehension:", even_squares_comprehension)
Even squares with loop: [0, 4, 16, 36, 64]
Even squares with comprehension: [0, 4, 16, 36, 64]
# Using nested loops to create a list of tuples
product_loop = []
for x in range(3):
    for y in range(3):
        product_loop.append((x, y))

# Using a nested list comprehension
product_comprehension = [(x, y) for x in range(3) for y in range(3)]

print("Product with loop:", product_loop)
print("Product with comprehension:", product_comprehension)
Product with loop: [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]
Product with comprehension: [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]
# List of lists
nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

# Flatten the list
flattened = [item for sublist in nested_list for item in sublist]

print("Flattened list:", flattened)
Flattened list: [1, 2, 3, 4, 5, 6, 7, 8, 9]
# Using `if` and `else` in a list comprehension
number_list = [x if x % 2 == 0 else -x for x in range(10)]

print("Number list with if-else:", number_list)
Number list with if-else: [0, -1, 2, -3, 4, -5, 6, -7, 8, -9]
keys = ["name", "age", "city"]
values = ["Alice", 25, "New York"]

# Creating a dictionary from two lists
my_dict = {k: v for k, v in zip(keys, values)}

print("Dictionary:", my_dict)
Dictionary: {'name': 'Alice', 'age': 25, 'city': 'New York'}
# List of strings
fruits = ["apple", "banana", "cherry", "date", "elderberry"]

# Filter fruits to include only those with more than 5 letters
filtered_fruits = [fruit for fruit in fruits if len(fruit) > 5]

print("Filtered fruits:", filtered_fruits)
Filtered fruits: ['banana', 'cherry', 'elderberry']
names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 35]

# List of dictionaries
people = [{"name": name, "age": age} for name, age in zip(names, ages)]

print("List of dictionaries:", people)
List of dictionaries: [{'name': 'Alice', 'age': 25}, {'name': 'Bob', 'age': 30}, {'name': 'Charlie', 'age': 35}]