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

  • Functions Returning Functions

    Understanding Functions Returning Functions In Python, functions can return other functions, which is a powerful feature of functional programming. Basic Example python def outer(): def inner(): print(“Welcome!”) return inner # Return the inner function (without calling it) # Calling outer() returns the inner function f = outer() # f now refers to the inner function…

  • date time modules class55

    In Python, the primary modules for handling dates and times are: 🕰️ Key Built-in Modules 1. datetime This is the most essential module. It provides classes for manipulating dates and times in both simple and complex ways. Class Description Example Usage date A date (year, month, day). date.today() time A time (hour, minute, second, microsecond,…

  • 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…

  • Challenge Summary: Inheritance – Polygon and Triangle Classes

    Challenge Summary: Inheritance – Polygon and Triangle Classes Objective: Create two classes where Triangle inherits from Polygon and calculates area using Heron’s formula. 1. Polygon Class (Base Class) Properties: Methods: __init__(self, num_sides, *sides) python class Polygon: def __init__(self, num_sides, *sides): self.number_of_sides = num_sides self.sides = list(sides) 2. Triangle Class (Derived Class) Inheritance: Methods: __init__(self, *sides) area(self) python import math…

  • Polymorphism

    Polymorphism is a core concept in OOP that means “many forms” 🐍. In Python, it allows objects of different classes to be treated as objects of a common superclass. This means you can use a single function or method to work with different data types, as long as they implement a specific action. 🌀 Polymorphism…

  • AttributeError: ‘NoneType’ Error in Python re

    AttributeError: ‘NoneType’ Error in Python re This error occurs when you try to call match object methods on None instead of an actual match object. It’s one of the most common errors when working with Python’s regex module. Why This Happens: The re.search(), re.match(), and re.fullmatch() functions return: When you try to call methods like .group(), .start(), or .span() on None, you get this error. Example That Causes…

Leave a Reply

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