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

  • Python Modules: Creation and Usage Guide

    Python Modules: Creation and Usage Guide What are Modules in Python? Modules are simply Python files (with a .py extension) that contain Python code, including: They help you organize your code into logical units and promote code reusability. Creating a Module 1. Basic Module Creation Create a file named mymodule.py: python # mymodule.py def greet(name): return f”Hello, {name}!”…

  • re.sub()

    Python re.sub() Method Explained The re.sub() method is used for searching and replacing text patterns in strings. It’s one of the most powerful regex methods for text processing. Syntax python re.sub(pattern, repl, string, count=0, flags=0) Example 1: Basic Text Replacement python import re text = “The color of the sky is blue. My favorite color is blue too.” #…

  • Strings in Python Indexing,Traversal

    Strings in Python and Indexing Strings in Python are sequences of characters enclosed in single quotes (‘ ‘), double quotes (” “), or triple quotes (”’ ”’ or “”” “””). They are immutable sequences of Unicode code points used to represent text. String Characteristics Creating Strings python single_quoted = ‘Hello’ double_quoted = “World” triple_quoted = ”’This is…

  • Linear vs. Scalar,Homogeneous vs. Heterogeneous 

    Linear vs. Scalar Data Types in Python In programming, data types can be categorized based on how they store and organize data. Two important classifications are scalar (atomic) types and linear (compound) types. 1. Scalar (Atomic) Data Types 2. Linear (Compound/Sequential) Data Types Key Differences Between Scalar and Linear Data Types Feature Scalar (Atomic) Linear (Compound) Stores Single…

  • Special Character Classes Explained with Examples

    Special Character Classes Explained with Examples 1. [\\\^\-\]] – Escaped special characters in brackets Description: Matches literal backslash, caret, hyphen, or closing bracket characters inside character classes Example 1: Matching literal special characters python import re text = “Special chars: \\ ^ – ] [” result = re.findall(r'[\\\^\-\]]’, text) print(result) # [‘\\’, ‘^’, ‘-‘, ‘]’] # Matches…

Leave a Reply

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