24.05.2017 07:57

Python Maps Tutorial

Author: Elliot Forbes | @Elliot_F

Table Of Contents

This tutorial was built using Python 3.6

Maps in Python are syntactic sugar that allow you to very succinctly iterate through every element of an array and perform a function on it.

Imagine we started off with a list of values numbering from 2-6 like so:

values = [2,3,4,5,6]

And we had a function which doubled said values:

def double(x):
  return x * 2

With the use of maps we would have to do something like so in order to multiply every element:

for value in values:
  value = double(value)

but with maps we can be far more succinct:

results = list(map(double, values))

Complete Example

Below you’ll find a complete exmaple for a simple map which applies the double function to every element in the values array.

values = [2,3,4,5,6]

def double(x):
  return x * 2

results = list(map(double, values))

this produces the following output:

[4, 6, 8, 10, 12, 14, 16]

See A Problem?

See something wrong with this page? Feel free to submit a pull request and help improve the development community!