List Comprehensions 

List Comprehensions in Python (Basic) with Examples

List comprehensions provide a concise way to create lists in Python. They are more readable and often faster than using loops.

Basic Syntax:

python

[expression for item in iterable if condition]

Example 1: Simple List Comprehension

Create a list of squares from 0 to 9.

Using Loop:

python

squares = []
for x in range(10):
    squares.append(x ** 2)
print(squares)  # Output: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

Using List Comprehension:

python

squares = [x ** 2 for x in range(10)]
print(squares)  # Output: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

Example 2: List Comprehension with Condition

Create a list of even numbers from 0 to 10.

Using Loop:

python

evens = []
for x in range(11):
    if x % 2 == 0:
        evens.append(x)
print(evens)  # Output: [0, 2, 4, 6, 8, 10]

Using List Comprehension:

python

evens = [x for x in range(11) if x % 2 == 0]
print(evens)  # Output: [0, 2, 4, 6, 8, 10]

Example 3: Nested List Comprehension

Convert a 2D list into a 1D list (flattening).

Given:

python

matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

Using Loop:

python

flattened = []
for row in matrix:
    for num in row:
        flattened.append(num)
print(flattened)  # Output: [1, 2, 3, 4, 5, 6, 7, 8, 9]

Using List Comprehension:

python

flattened = [num for row in matrix for num in row]
print(flattened)  # Output: [1, 2, 3, 4, 5, 6, 7, 8, 9]

Example 4: List Comprehension with if-else

Convert numbers to “even” or “odd” in a list.

Using Loop:

python

numbers = [1, 2, 3, 4, 5]
result = []
for x in numbers:
    if x % 2 == 0:
        result.append("even")
    else:
        result.append("odd")
print(result)  # Output: ['odd', 'even', 'odd', 'even', 'odd']

Using List Comprehension:

python

numbers = [1, 2, 3, 4, 5]
result = ["even" if x % 2 == 0 else "odd" for x in numbers]
print(result) # Output: ['odd', 'even', 'odd', 'even', 'odd']

1. Filtering with Multiple Conditions

Get numbers between 10 and 50 that are divisible by 3 or 7.

Using Loop:

python

result = []
for num in range(10, 51):
    if num % 3 == 0 or num % 7 == 0:
        result.append(num)

Using List Comprehension:

python

result = [num for num in range(10, 51) if num % 3 == 0 or num % 7 == 0]
# Output: [12, 14, 15, 18, 21, 24, 27, 28, 30, 33, 35, 36, 39, 42, 45, 48, 49]

2. Applying Functions to Elements

Convert a list of strings to uppercase and exclude short words (length < 4).

Using Loop:

python

words = ["apple", "cat", "dog", "banana", "kiwi"]
filtered = []
for word in words:
    if len(word) >= 4:
        filtered.append(word.upper())

Using List Comprehension:

python

words = ["apple", "cat", "dog", "banana", "kiwi"]
filtered = [word.upper() for word in words if len(word) >= 4]
# Output: ['APPLE', 'BANANA', 'KIWI']

3. Creating a List of Tuples (Cartesian Product)

Generate all possible (x, y) pairs where x is from [1, 2, 3] and y is from ['a', 'b'].

Using Loop:

python

pairs = []
for x in [1, 2, 3]:
    for y in ['a', 'b']:
        pairs.append((x, y))

Using List Comprehension:

python

pairs = [(x, y) for x in [1, 2, 3] for y in ['a', 'b']]
# Output: [(1, 'a'), (1, 'b'), (2, 'a'), (2, 'b'), (3, 'a'), (3, 'b')]

4. Flattening a 2D List with Condition

Extract even numbers from a nested list.

Given:

python

matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

Using Loop:

python

evens = []
for row in matrix:
    for num in row:
        if num % 2 == 0:
            evens.append(num)

Using List Comprehension:

python

evens = [num for row in matrix for num in row if num % 2 == 0]
# Output: [2, 4, 6, 8]

5. Dictionary Comprehension Inside List Comprehension

Convert a list of names into a list of dictionaries with name and length keys.

Using Loop:

python

names = ["Alice", "Bob", "Charlie"]
result = []
for name in names:
    result.append({"name": name, "length": len(name)})

Using List Comprehension:

python

names = ["Alice", "Bob", "Charlie"]
result = [{"name": name, "length": len(name)} for name in names]
# Output: [{'name': 'Alice', 'length': 5}, {'name': 'Bob', 'length': 3}, {'name': 'Charlie', 'length': 7}]

6. Using enumerate() in List Comprehension

Get only even-indexed elements from a list.

Using Loop:

python

fruits = ["apple", "banana", "cherry", "date", "elderberry"]
filtered = []
for i, fruit in enumerate(fruits):
    if i % 2 == 0:
        filtered.append(fruit)

Using List Comprehension:

python

fruits = ["apple", "banana", "cherry", "date", "elderberry"]
filtered = [fruit for i, fruit in enumerate(fruits) if i % 2 == 0]
# Output: ['apple', 'cherry', 'elderberry']

7. Simulating zip() with List Comprehension

Combine two lists element-wise.

Given:

python

names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 35]

Using Loop:

python

combined = []
for name, age in zip(names, ages):
    combined.append(f"{name} is {age} years old")

Using List Comprehension:

python

combined = [f"{name} is {age} years old" for name, age in zip(names, ages)]
# Output: ['Alice is 25 years old', 'Bob is 30 years old', 'Charlie is 35 years old']

8. Handling Exceptions in List Comprehension

Convert strings to integers safely, ignoring invalid entries.

Using Loop:

python

data = ["10", "20", "thirty", "40"]
numbers = []
for item in data:
    try:
        numbers.append(int(item))
    except ValueError:
        pass

Using List Comprehension (with a helper function):

python

def safe_int(x):
    try:
        return int(x)
    except ValueError:
        return None

data = ["10", "20", "thirty", "40"]
numbers = [safe_int(x) for x in data if safe_int(x) is not None]
# Output: [10, 20, 40]

Similar Posts

  • The Fractions module

    The Fractions module in Python is a built-in module that provides support for rational number arithmetic. It allows you to work with fractions (like 1/2, 3/4, etc.) exactly, without the precision issues that can occur with floating-point numbers. What Problems Does It Solve? Problem with Floating-Point Numbers: python # Floating-point precision issue print(0.1 + 0.2) # Output:…

  • math Module

    The math module in Python is a built-in module that provides access to standard mathematical functions and constants. It’s designed for use with complex mathematical operations that aren’t natively available with Python’s basic arithmetic operators (+, -, *, /). Key Features of the math Module The math module covers a wide range of mathematical categories,…

  • Nested for loops, break, continue, and pass in for loops

    break, continue, and pass in for loops with simple examples. These statements allow you to control the flow of execution within a loop. 1. break Statement The break statement is used to terminate the loop entirely. When break is encountered, the loop immediately stops, and execution continues with the statement immediately following the loop. Example:…

  • Currency Converter

    Challenge: Currency Converter Class with Accessors & Mutators Objective: Create a CurrencyConverter class that converts an amount from a foreign currency to your local currency, using accessor and mutator methods. 1. Class Properties (Instance Variables) 2. Class Methods 3. Task Instructions

Leave a Reply

Your email address will not be published. Required fields are marked *