Let’s look at Python’s **map** function. What does this function do? Here is the syntax:

1 |
map(function, iterable, ...) |

It takes a function called **function** and applies it to each element of **iterable**, returning the result as an iterable. For example:

1 2 3 4 5 |
myList = [1,2,3,4] myList = map(lambda x:x**2 ,myList) for i in myList: print(i) |

The output of this program is:

1 2 3 4 |
1 4 9 16 |

If you want to convert the returned iterable back into a list, that’s easy:

1 2 3 |
myList = [1,2,3,4] myList = list(map(lambda x:x**2 ,myList)) print(myList) |

The output here is “[1, 4, 9, 16]”. Using **map** is cleaner and easier than writing a loop. What are some uses of this feature? Let’s look at a real-world example using Sage, that often comes up in mathematical programming.

Let’s suppose you have a list containing all the elements of a finite set $S$. Say for concreteness your list is [a,x,0,y,m]. You permute this list to [x,m,y,a,0]. What is the corresponding permutation in cycle notation?

Sage has a function **PermutationGroupElement** that takes a permuted list of positive integers and returns the corresponding permutation in cycle notation. For instance:

1 2 3 4 |
PermutationGroupElement([1,2,3]) > () PermutationGroupElement([1,4,2,3]) > (2,4,3) |

Here, I’ve indicated the output of the function with an angle bracket. But this function only takes lists of positive integers. Here is how to use the map function to quickly convert a custom permuted list to a list of positive integers so that it works with the function **PermutationGroupElement**:

1 2 3 4 5 6 |
var('a','x','y','m') originalList = [a,x,0,y,m] permutedList = [x,m,y,a,0] intList = list(map( lambda x:originalList.index(x)+1, permutedList ) ) print(intList) PermutationGroupElement(intList) |

This code prints “(1,2,5,3,4)”, which is exactly the cycle notation for the permutation that takes **originalList** to **permutedList**. Notice that we had to add one to the index, because indices in Python start at zero, whereas permutation groups in Sage canonically operate on finite sets of positive integers, starting at one.

In general, if you need to make a new list (or just iterate over the elements of a new list) from an old one, chances are you should use **map** instead of writing a loop.