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

  • Quantifiers (Repetition)

    Quantifiers (Repetition) in Python Regular Expressions – Detailed Explanation Basic Quantifiers 1. * – 0 or more occurrences (Greedy) Description: Matches the preceding element zero or more times Example 1: Match zero or more digits python import re text = “123 4567 89″ result = re.findall(r’\d*’, text) print(result) # [‘123’, ”, ‘4567’, ”, ’89’, ”] # Matches…

  • circle,Rational Number

    1. What is a Rational Number? A rational number is any number that can be expressed as a fraction where both the numerator and the denominator are integers (whole numbers), and the denominator is not zero. The key idea is ratio. The word “rational” comes from the word “ratio.” General Form:a / b Examples: Non-Examples: 2. Formulas for Addition and Subtraction…

  • Raw Strings in Python

    Raw Strings in Python’s re Module Raw strings (prefixed with r) are highly recommended when working with regular expressions because they treat backslashes (\) as literal characters, preventing Python from interpreting them as escape sequences. path = ‘C:\Users\Documents’ pattern = r’C:\Users\Documents’ .4.1.1. Escape sequences Unless an ‘r’ or ‘R’ prefix is present, escape sequences in string and bytes literals are interpreted according…

  • re.findall()

    Python re.findall() Method Explained The re.findall() method returns all non-overlapping matches of a pattern in a string as a list of strings or tuples. Syntax python re.findall(pattern, string, flags=0) Key Characteristics: Example 1: Extracting All Numbers from Text python import retext = “I bought 5 apples for $3.50, 2 bananas for $1.25, and 10 oranges for $7.80.”result = re.findall(r”\d{3}”,…

  • Mathematical Functions

    1. abs() Syntax: abs(x)Description: Returns the absolute value (non-negative value) of a number. Examples: python # 1. Basic negative numbers print(abs(-10)) # 10 # 2. Positive numbers remain unchanged print(abs(5.5)) # 5.5 # 3. Floating point negative numbers print(abs(-3.14)) # 3.14 # 4. Zero remains zero print(abs(0)) # 0 # 5. Complex numbers (returns magnitude) print(abs(3 +…

Leave a Reply

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