Introduction and Overview

Hello, aspiring astronaut! Today, we're delving deeper into the universe of Python with a special emphasis on more complex built-in functions. We'll decipher the mysteries of map(), filter(), and zip(). Employing these functions can simplify our code, so fasten your seatbelts!

Diving into the map() Function

We begin with map(), a tool akin to a space probe that applies the same function on each item of a list. Here's how to utilize it: map(func, list). Let's apply it to double the numbers in a list:

def double(num): # Our function that doubles the input number
    return num * 2

numbers = [1, 2, 3, 4, 5]  # Our list 
doubled_numbers = list(map(double, numbers))  # Applying `double` function to each element of the list

print(doubled_numbers)  # Output: [2, 4, 6, 8, 10]

Excellent work! With map(), we've doubled the items in our list.

Exploring the filter() Function

Next up is filter(). It sifts out items based on a condition, acting like a cosmic patrol, filtering only those elements of the list that satisfy the provided condition (filter). It operates similarly to map(), except the function must return True or False. Let's extract the even numbers:

def is_even(num): # Our function, returning True only for even numbers
    return num % 2 == 0

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]  # Our list

even_numbers = list(filter(is_even, numbers))  # Filtering even numbers

print(even_numbers)  # Output: [2, 4, 6, 8, 10]

Congratulations! We've used filter() to include only even numbers!

Getting a Grip on the zip() Function

Finally, let's demystify the zip() function. It combines multiple lists, much like a bridge in spacetime. zip() returns a list of pairs (tuples) - a pair of the first elements from both lists, a pair of the second elements from both lists, etc. Let's observe it in action as it pairs names with ages:

names = ["John", "Sara", "Tim", "Lisa"]  # List of names
ages = [25, 30, 35, 28]  # List of ages

names_ages = list(zip(names, ages))  # Zipping lists into tuples

print(names_ages)  # Output: [('John', 25), ('Sara', 30), ('Tim', 35), ('Lisa', 28)]

Cheers, astronauts! We've watched zip() unite names and ages, forming tuples.

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal