Menu
Coddy logo textTech

Mapping

Lesson 2 of 9 in Coddy's Python List Comprehension course.

Let's assume you are given list of numbers, and you want to calculate a string which holds the cubes of all the number,

nums = [1, 4, 6, 12, 3]
cubes = []
for n in nums:
	cubes.append(n ** 3)

print(cubes)  # [1 , 16, 36, 144, 9]

Using list comprehension it can be done in one line,

nums = [1, 4, 6, 12, 3]
cubes = [n ** 3 for n in nums]

print(cubes)  # [1 , 16, 36, 144, 9]

This kind of operations called mapping - applying a function to each element of an existing list and generating a new list containing the results.

Here is the syntax,

lst = [expression for item in iterable]

lst will hold a new list resulted from the list comprehension operation.

challenge icon

Challenge

Easy

Given a list of number nums, Assuming each element is x, calculate a new list where each element is calculated with the following equation: <strong>x<sup>3</sup>+2*x<sup>2</sup>+5</strong>

Store the new list in a variable named new_nums.

Try it yourself

nums = eval(input())  # Don't change this line

All lessons in Python List Comprehension