Sun 25 January 2015

Filed under Python


First: What is 'map'?

In very short, map runs the given function over the given iterable.

For example: We have a function that converts years to their Roman numeral version. And we have a list of years. We can run a map(convert_year_to_roman_numeral, ['1999', '1776', '2015']. This will run the function convert_year_to_roman_numeral on the list of years. And return the Roman numerals for those years. As a list.

The Syntax

map(function, iterable)

  • The function can be a function or a lambda expression.

  • The iterable can be any iterable - list, string, etc.

A few examples:

map(lambda x: x**2, [1, 2, 3, 4])

  • The function here is a lambda.
  • The iterable is the list.
  • This runs the lambda (x**2) on the first item in the iterable - on the 1.
  • Then runs the lambda on the next item in the iterable, and so on. Until all items have been run.
  • The result is [1, 4, 9, 16]
    def sqr(num):
        return num **2
    seq = [1, 2, 3, 4]

  • This runs exactly as above.
  • It runs the sqr function on the seq. And run the function on every item in the iterable.

Comments © Dee Kras Powered by Pelican and Twitter Bootstrap. Icons by Font Awesome and Font Awesome More