Lesson 4

Unraveling Python's Complex Built-in Functions: A Galactic Tour of map(), filter(), and zip() Functions

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:

1def double(num): # Our function that doubles the input number 2 return num * 2 3 4numbers = [1, 2, 3, 4, 5] # Our list 5doubled_numbers = list(map(double, numbers)) # Applying `double` function to each element of the list 6 7print(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:

1def is_even(num): # Our function, returning True only for even numbers 2 return num % 2 == 0 3 4numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] # Our list 5 6even_numbers = list(filter(is_even, numbers)) # Filtering even numbers 7 8print(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:

1names = ["John", "Sara", "Tim", "Lisa"] # List of names 2ages = [25, 30, 35, 28] # List of ages 3 4names_ages = list(zip(names, ages)) # Zipping lists into tuples 5 6print(names_ages) # Output: [('John', 25), ('Sara', 30), ('Tim', 35), ('Lisa', 28)]

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

Lesson Summary

Excellent explorations, astronauts! We've untangled the complexities of map(), filter(), and zip(). Our learning journey promises to continue with hands-on practices next. By resolving diverse problems, you'll cement your understanding. As the adage goes, you learn to code by coding! So, prepare for hands-on coding missions. Safe journey, space commanders!

Enjoy this lesson? Now it's time to practice with Cosmo!

Practice is how you turn knowledge into actual skills.