Skip to content

Advanced Comprehensions and Nested Loops in Python ๐Ÿš€ โ€‹

Welcome back, aspiring hero! In this chapter, we'll dive deep into the advanced realms of Python programming, exploring all types of comprehensions and mastering nested loops. These powerful tools will enhance your coding superpowers, allowing you to write more efficient and elegant code.

Nested Loops: The Power of Layers ๐ŸŒ€ โ€‹

Nested loops are like layers of strategy that superheroes use to tackle complex challenges. By placing one loop inside another, you can perform repeated actions within repeated actions.

Example: The Multiplication Table โ€‹

python
# Generating a multiplication table
for i in range(1, 6):  # Outer loop
    for j in range(1, 6):  # Inner loop
        print(f"{i * j:2}", end=" ")
    print()  # Newline after each row

Output:

 1  2  3  4  5
 2  4  6  8 10
 3  6  9 12 15
 4  8 12 16 20
 5 10 15 20 25

Explanation: The outer loop runs through numbers 1 to 5, and for each iteration, the inner loop also runs from 1 to 5, multiplying the outer and inner loop variables.

All Types of Comprehensions ๐Ÿง  โ€‹

Python offers several types of comprehensions for creating sequences in a concise way:

  • List Comprehensions
  • Dictionary Comprehensions
  • Set Comprehensions
  • Generator Expressions

List Comprehensions ๐Ÿ“‹ โ€‹

List comprehensions provide a concise way to create lists.

Basic Syntax โ€‹

python
[expression for item in iterable if condition]

Examples โ€‹

  • Squaring Numbers

    python
    numbers = [1, 2, 3, 4, 5]
    squares = [num ** 2 for num in numbers]
    print(squares)
    # Output: [1, 4, 9, 16, 25]
  • Filtering Even Numbers

    python
    even_numbers = [num for num in numbers if num % 2 == 0]
    print(even_numbers)
    # Output: [2, 4]

Task: Non-Mutating Amplification ๐Ÿงช โ€‹

Task

Create a function amplify_stats_non_mutating that returns a new list with amplified stats, without modifying the original list.

Hint: Use list comprehension.

Answer
python
def amplify_stats_non_mutating(stats):
    return [stat * 2 for stat in stats]

original_stats = [10, 20, 30, 40]
amplified_stats = amplify_stats_non_mutating(original_stats)
print("Original Stats:", original_stats)
print("Amplified Stats:", amplified_stats)

Output:

Original Stats: [10, 20, 30, 40]
Amplified Stats: [20, 40, 60, 80]

List Comprehensions: The Super Speed Technique โšก โ€‹

Question: How can superheroes process data quickly?

List comprehensions provide a concise way to create lists.

python
marks = [90, 30, 20, 80, 50]

# Filter passing marks (>= 40)
passing_marks = [mark for mark in marks if mark >= 40]
print("Passing Marks:", passing_marks)

Output:

Passing Marks: [90, 80, 50]

Task: Filtering Heroes by Name Length ๐Ÿฆธโ€โ™€๏ธ โ€‹

Given a list of hero names, extract the names that have 10 or more characters.

Example:

python
heroes = ["Hulk", "Iron Man", "Black Widow", "Captain America", "Spider-Man", "Thor"]

Task

Use list comprehension to get heroes with names longer than or equal to 10 characters.

Answer
python
long_named_heroes = [hero for hero in heroes if len(hero) >= 10]
print("Heroes with long names:", long_named_heroes)

Output:

Heroes with long names: ['Black Widow', 'Captain America', 'Spider-Man']

Calculating Distances: Mapping the Hero's Journey ๐Ÿ—บ๏ธ โ€‹

Superheroes often need to calculate distances to reach their destinations.

Scenario: Given coordinates of various locations (islands), calculate the distance from the origin (0, 0) to each location.

python
import math

islands = [(5, 4), (1, 1), (6, 10), (9, 10)]

def calculate_distances(islands):
    return [math.hypot(x, y) for x, y in islands]

distances = calculate_distances(islands)
print("Distances to islands:", distances)

Output:

Distances to islands: [6.4031242374328485, 1.4142135623730951, 11.661903789690601, 13.45362404707371]

Task: Finding the Closest Island ๐Ÿ๏ธ โ€‹

Task

Using the distances calculated, determine which island is the closest to the origin.

Hint: Use the min() function along with the distances list.

Answer
python
min_distance = min(distances)
closest_island_index = distances.index(min_distance)
closest_island = islands[closest_island_index]
print(f"The closest island is at {closest_island} with a distance of {min_distance}")

Output:

The closest island is at (1, 1) with a distance of 1.4142135623730951

Understanding Mutable vs Immutable Operations ๐Ÿ”„๐Ÿ”’ โ€‹

Question: What's the difference between modifying an existing list and creating a new one?

  • Mutable Operation: Changes the original list.
  • Immutable Operation: Creates a new list, leaving the original unchanged.

Example of Mutable Operation:

python
def double_stats_mutate(stats):
    for i in range(len(stats)):
        stats[i] *= 2

player_stats = [10, 20, 30, 40]
double_stats_mutate(player_stats)
print("After mutation:", player_stats)

Output:

After mutation: [20, 40, 60, 80]

Example of Immutable Operation:

python
def double_stats_immutable(stats):
    return [stat * 2 for stat in stats]

player_stats = [10, 20, 30, 40]
new_stats = double_stats_immutable(player_stats)
print("Original Stats:", player_stats)
print("New Stats:", new_stats)

Output:

Original Stats: [10, 20, 30, 40]
New Stats: [20, 40, 60, 80]

Task: Implementing an Immutable Function ๐Ÿ› ๏ธ โ€‹

Task

Write a function increase_power that takes a list of powers and returns a new list with each power increased by 10, without modifying the original list.

Answer
python
def increase_power(powers):
    return [power + 10 for power in powers]

original_powers = [50, 60, 70]
new_powers = increase_power(original_powers)
print("Original Powers:", original_powers)
print("Increased Powers:", new_powers)

Output:

Original Powers: [50, 60, 70]
Increased Powers: [60, 70, 80]

Advanced List Comprehension: Combining Techniques ๐Ÿš€ โ€‹

We can combine list comprehension with functions and unpacking for more complex operations.

Example:

python
def distance_formula(x, y):
    return (x**2 + y**2)**0.5

def calculate_distances(islands):
    return [distance_formula(x, y) for x, y in islands]

print("Distances to islands:", calculate_distances(islands))

Task: Calculating Distances with Altitude ๐Ÿ›ฐ๏ธ โ€‹

Suppose each island also has an altitude (z-coordinate). The coordinates are now 3D:

python
islands_3d = [(5, 4, 1), (1, 1, 2), (6, 10, 3), (9, 10, 4)]

Task

Modify the distance_formula to calculate the distance from the origin in 3D space and compute the distances for islands_3d.

Answer
python
def distance_formula_3d(x, y, z):
    return (x**2 + y**2 + z**2)**0.5

def calculate_distances_3d(islands):
    return [distance_formula_3d(x, y, z) for x, y, z in islands]

print("Distances to islands in 3D:", calculate_distances_3d(islands_3d))

Output:

Distances to islands in 3D: [6.48074069840786, 2.449489742783178, 12.083045973594572, 14.212670403551895]

Dictionary Comprehensions ๐Ÿ—๏ธ โ€‹

Unlock the power of creating dictionaries in a single line! Dictionary comprehensions are like magic spells for data mapping. ๐Ÿช„

Basic Syntax โ€‹

python
{key_expression: value_expression for item in iterable if condition}

Examples โ€‹

  • Creating a Dictionary of Squares ๐Ÿ“

    python
    numbers = [1, 2, 3, 4, 5]
    squares_dict = {num: num ** 2 for num in numbers}
    print(squares_dict)
    # Output: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

    Explanation: For each number in the list, we're creating a key-value pair where the key is the number and the value is its square. โšก

  • Inverting a Dictionary ๐Ÿ”„

    python
    original_dict = {'a': 1, 'b': 2, 'c': 3}
    inverted_dict = {value: key for key, value in original_dict.items()}
    print(inverted_dict)
    # Output: {1: 'a', 2: 'b', 3: 'c'}

    Explanation: Switch the keys and valuesโ€”because who doesn't like a little role reversal? ๐Ÿ˜Ž

Set Comprehensions ๐Ÿ”ข โ€‹

Sets are like the exclusive clubs of the data worldโ€”no duplicates allowed! Set comprehensions let you build these unique collections effortlessly. ๐Ÿฅณ

Basic Syntax โ€‹

python
{expression for item in iterable if condition}

Examples โ€‹

  • Unique Squares ๐Ÿงฎ

    python
    numbers = [1, 2, 2, 3, 4, 4, 5]
    unique_squares = {num ** 2 for num in numbers}
    print(unique_squares)
    # Output: {1, 4, 9, 16, 25}

    Explanation: Even with duplicate numbers, the set keeps only unique squares! It's like having superpowers to eliminate duplicates! ๐Ÿฆธโ€โ™€๏ธ

Generator Expressions โš™๏ธ โ€‹

Generator expressions are like the ninjas of Pythonโ€”they do their work stealthily and efficiently! ๐Ÿคซ They generate items on the fly without storing the entire sequence in memory.

Basic Syntax โ€‹

python
(expression for item in iterable if condition)

Examples โ€‹

  • Sum of Squares โž•

    python
    numbers = [1, 2, 3, 4, 5]
    sum_of_squares = sum(num ** 2 for num in numbers)
    print(sum_of_squares)
    # Output: 55

    Explanation: We calculate the sum without creating an intermediate list. Memory-efficient and lightning-fast! โšก

Nested Comprehensions ๐ŸŒ โ€‹

Just like dreams within dreams in "Inception," we can have comprehensions within comprehensions! ๐ŸŒ€

Example: Flattening a Matrix ๐Ÿ—บ๏ธ โ€‹

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

Explanation: We're traversing each row and then each number within that row to create a single flattened list. It's like unraveling a complex puzzle! ๐Ÿงฉ

Example: Multiplication Table Using Comprehensions ๐Ÿ“Š โ€‹

python
table = [[i * j for j in range(1, 6)] for i in range(1, 6)]
for row in table:
    print(row)
# Output:
# [1, 2, 3, 4, 5]
# [2, 4, 6, 8, 10]
# [3, 6, 9, 12, 15]
# [4, 8, 12, 16, 20]
# [5, 10, 15, 20, 25]

Explanation: A nested comprehension generates a 5x5 multiplication table. Time to flex those math muscles! ๐Ÿ’ช

Advanced Examples with Comprehensions ๐Ÿง  โ€‹

Filtering and Transforming Data ๐ŸŽฏ โ€‹

Let's work with a team of superheroes! ๐Ÿฆธโ€โ™‚๏ธ๐Ÿฆธโ€โ™€๏ธ

python
heroes = [
    {'name': 'Spider-Man', 'power': 'Web-slinging', 'age': 18},
    {'name': 'Iron Man', 'power': 'Armor Suit', 'age': 45},
    {'name': 'Thor', 'power': 'God of Thunder', 'age': 1500},
    {'name': 'Black Widow', 'power': 'Espionage', 'age': 34}
]

# Get names of heroes older than 100
ancient_heroes = [hero['name'] for hero in heroes if hero['age'] > 100]
print(ancient_heroes)
# Output: ['Thor']

Explanation: Only the mightiest (and oldest) heroes make the cut! โš”๏ธ

Dictionary Comprehension with Conditional Logic ๐Ÿง™โ€โ™‚๏ธ โ€‹

python
# Assign 'Veteran' or 'Rookie' status based on age
status_dict = {
    hero['name']: ('Veteran' if hero['age'] > 40 else 'Rookie')
    for hero in heroes
}
print(status_dict)
# Output: {'Spider-Man': 'Rookie', 'Iron Man': 'Veteran', 'Thor': 'Veteran', 'Black Widow': 'Veteran'}

Explanation: Classify heroes based on experience. Who's got the most battle scars? ๐Ÿ›ก๏ธ

Nested Loops with Complex Data Structures ๐Ÿ—๏ธ โ€‹

Processing a List of Dictionaries ๐Ÿ“š โ€‹

Team assembly time! Let's list all team members. ๐ŸŽฌ

python
teams = [
    {
        'team_name': 'Avengers',
        'members': ['Iron Man', 'Thor', 'Hulk']
    },
    {
        'team_name': 'Guardians',
        'members': ['Star-Lord', 'Rocket', 'Groot']
    }
]

# Roll call!
for team in teams:
    print(f"Team: {team['team_name']} ๐Ÿš€")
    for member in team['members']:
        print(f"- {member}")
# Output:
# Team: Avengers ๐Ÿš€
# - Iron Man
# - Thor
# - Hulk
# Team: Guardians ๐Ÿš€
# - Star-Lord
# - Rocket
# - Groot

Explanation: We use nested loops to iterate over teams and their members. Teamwork makes the dream work! ๐Ÿค

๐Ÿ“ Task: Create a Complex Dictionary Using Comprehensions โ€‹

Objective: Given a list of numbers, create a dictionary where each key is the number and the value is another dictionary containing the square and cube of the number. ๐Ÿงฎ

Example:

python
numbers = [1, 2, 3, 4, 5]

Expected Output:

python
{
    1: {'square': 1, 'cube': 1},
    2: {'square': 4, 'cube': 8},
    3: {'square': 9, 'cube': 27},
    4: {'square': 16, 'cube': 64},
    5: {'square': 25, 'cube': 125}
}

Solution:

python
numbers = [1, 2, 3, 4, 5]
number_powers = {
    num: {'square': num ** 2, 'cube': num ** 3}
    for num in numbers
}
print(number_powers)

Explanation: We're nesting dictionaries inside a dictionary comprehension. It's like building data structures within data structuresโ€”data-ception! ๐Ÿง

Combining Comprehensions and Functions ๐Ÿงฌ โ€‹

Using Functions Inside Comprehensions ๐Ÿงช โ€‹

Let's find prime numbersโ€”because prime numbers are like the superheroes of the number world! ๐Ÿ’ซ

python
def is_prime(n):
    if n <= 1:
        return False
    for i in range(2, int(n ** 0.5) + 1):
        if n % i == 0:
            return False
    return True

# List of prime numbers between 1 and 20
primes = [num for num in range(1, 21) if is_prime(num)]
print(primes)
# Output: [2, 3, 5, 7, 11, 13, 17, 19]

Explanation: We use the is_prime function within a list comprehension to filter out prime numbers. Math meets codingโ€”what a combo! ๐Ÿค“

Advanced Nested Comprehensions ๐ŸŽฏ โ€‹

Creating a 2D Grid ๐ŸŒ โ€‹

Build a coordinate grid using nested comprehensions. Let's map out our hero's city! ๐Ÿ™๏ธ

python
grid_size = 3
grid = [[(i, j) for j in range(grid_size)] for i in range(grid_size)]
for row in grid:
    print(row)
# Output:
# [(0, 0), (0, 1), (0, 2)]
# [(1, 0), (1, 1), (1, 2)]
# [(2, 0), (2, 1), (2, 2)]

Explanation: We're creating a grid of coordinate pairs. Perfect for game development or mapping! ๐Ÿ—บ๏ธ

Flattening Nested Lists ๐Ÿงน โ€‹

Clean up nested lists with a comprehension broom! ๐Ÿงน

python
nested_list = [[1, 2], [3, 4], [5, 6]]
flattened = [item for sublist in nested_list for item in sublist]
print(flattened)
# Output: [1, 2, 3, 4, 5, 6]

Explanation: We flatten the nested lists into a single list. Simplicity is the ultimate sophistication! โœจ

๐Ÿ’Ž Task: Build a Set of Unique Characters โ€‹

Objective: Given a list of words, create a set of all unique characters used in these words.

Example:

python
words = ["hero", "villain", "sidekick"]

Expected Output:

python
{'h', 'e', 'r', 'o', 'v', 'i', 'l', 'a', 'n', 's', 'd', 'k', 'c'}

Solution:

python
words = ["hero", "villain", "sidekick"]
unique_chars = {char for word in words for char in word}
print(unique_chars)

Explanation: We're collecting unique characters from all words using a set comprehension. It's like gathering all the infinity stones! ๐Ÿ’Ž

Conclusion ๐ŸŽ“ โ€‹

Congratulations, coding hero! ๐ŸŽ‰ You've leveled up by mastering advanced comprehensions and nested loops in Python. These tools will help you write cleaner, more efficient codeโ€”just like a superhero mastering new abilities!

Farewell, Coding Champion! ๐Ÿ‘‹ โ€‹

Keep pushing the boundaries, and may your code be as mighty as Thor's hammer and as swift as Flash! Until next time, happy coding! ๐Ÿš€