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

  • Curly Braces {} ,Pipe (|) Metacharacters

    Curly Braces {} in Python Regex Curly braces {} are used to specify exact quantity of the preceding character or group. They define how many times something should appear. Basic Syntax: Example 1: Exact Number of Digits python import re text = “Zip codes: 12345, 9876, 123, 123456, 90210″ # Match exactly 5 digits pattern = r”\d{5}” # Exactly…

  • Static Methods

    The primary use of a static method in Python classes is to define a function that logically belongs to the class but doesn’t need access to the instance’s data (like self) or the class’s state (like cls). They are essentially regular functions that are grouped within a class namespace. Key Characteristics and Use Cases General…

  • Python and PyCharm Installation on Windows: Complete Beginner’s Guide 2025

    Installing Python and PyCharm on Windows is a straightforward process. Below are the prerequisites and step-by-step instructions for installation. Prerequisites for Installing Python and PyCharm on Windows Step-by-Step Guide to Install Python on Windows Step 1: Download Python Step 2: Run the Python Installer Step 3: Verify Python Installation If Python is installed correctly, it…

  • Create lists

    In Python, there are multiple ways to create lists, depending on the use case. Below are the most common methods: 1. Direct Initialization (Using Square Brackets []) The simplest way to create a list is by enclosing elements in square brackets []. Example: python empty_list = [] numbers = [1, 2, 3, 4] mixed_list = [1, “hello”, 3.14,…

  • re.split()

    Python re.split() Method Explained The re.split() method splits a string by the occurrences of a pattern. It’s like the built-in str.split() but much more powerful because you can use regex patterns. Syntax python re.split(pattern, string, maxsplit=0, flags=0) Example 1: Splitting by Multiple Delimiters python import retext1=”The re.split() method splits a string by the occurrences of a pattern. It’s like…

  • Python timedelta Explained

    Python timedelta Explained timedelta is a class in Python’s datetime module that represents a duration – the difference between two dates or times. It’s incredibly useful for date and time arithmetic. Importing timedelta python from datetime import timedelta, datetime, date Basic Syntax python timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0) Examples 1. Basic timedelta Creation python from datetime…

Leave a Reply

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