Get Started

Built-in practice: map()

In this exercise, you'll practice using Python's built-in map() function to apply a function to every element of an object. Let's look at a list of party guests:

names = ['Jerry', 'Kramer', 'Elaine', 'George', 'Newman']

Suppose you wanted to create a new list (called names_uppercase) that converted all the letters in each name to uppercase. you could accomplish this with the below for loop:

names_uppercase = []

for name in names:
  names_uppercase.append(name.upper())

['JERRY', 'KRAMER', 'ELAINE', 'GEORGE', 'NEWMAN']

Let's explore using the map() function to do this more efficiently in one line of code.

This is a part of the course

“Writing Efficient Python Code”

View Course

Exercise instructions

  • Use map() and the method str.upper() to convert each name in the list names to uppercase. Save this to the variable names_map.
  • Print the data type of names_map.
  • Unpack the contents of names_map into a list called names_uppercase using the star character (*).
  • Print names_uppercase and observe its contents.

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

# Use map to apply str.upper to each element in names
names_map  = ____(____, ____)

# Print the type of the names_map
print(____(____))

# Unpack names_map into a list
names_uppercase = [____]

# Print the list created above
print(____)

This exercise is part of the course

Writing Efficient Python Code

IntermediateSkill Level
4.7+
53 reviews

Learn to write efficient code that executes quickly and allocates resources skillfully to avoid unnecessary overhead.

In this chapter, you'll learn what it means to write efficient Python code. You'll explore Python's Standard Library, learn about NumPy arrays, and practice using some of Python's built-in tools. This chapter builds a foundation for the concepts covered ahead.

Exercise 1: Welcome!Exercise 2: Pop quiz: what is efficientExercise 3: A taste of things to comeExercise 4: Zen of PythonExercise 5: Building with built-insExercise 6: Built-in practice: range()Exercise 7: Built-in practice: enumerate()Exercise 8: Built-in practice: map()
Exercise 9: The power of NumPy arraysExercise 10: Practice with NumPy arraysExercise 11: Bringing it all together: Festivus!

What is DataCamp?

Learn the data skills you need online at your own pace—from non-coding essentials to data science and machine learning.

Start Learning for Free