Basic use of map itertools.imap and future builtins.map

suggest change

The map function is the simplest one among Python built-ins used for functional programming. map() applies a specified function to each element in an iterable:

names = ['Fred', 'Wilma', 'Barney']

In Python 3:

map(len, names)  # map in Python 3.x is a class; its instances are iterable
# Out: <map object at 0x00000198B32E2CF8>

A Python 3-compatible map is included in the future_builtins module:

from future_builtins import map  # contains a Python 3.x compatible map()
map(len, names)                  # see below
# Out: <itertools.imap instance at 0x3eb0a20>

Alternatively, in Python 2 one can use imap from itertools to get a generator

map(len, names)   # map() returns a list
# Out: [4, 5, 6]

from itertools import imap
imap(len, names)  # itertools.imap() returns a generator
# Out: <itertools.imap at 0x405ea20>

The result can be explicitly converted to a list to remove the differences between Python 2 and 3:

list(map(len, names))
# Out: [4, 5, 6]

map() can be replaced by an equivalent list comprehension or generator expression:

[len(item) for item in names] # equivalent to Python 2.x map()
# Out: [4, 5, 6]

(len(item) for item in names) # equivalent to Python 3.x map()
# Out: <generator object <genexpr> at 0x00000195888D5FC0>

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Map Function:
* Basic use of map itertools.imap and future builtins.map

Table Of Contents
2 Filter
3 List
7 Loops
22 Reduce
23 Map Function
27 Classes
31 Set
42 Tuple
45 Enum
62 Sockets
89 urllib
92 Idioms
104 Stack
105 Profiling
109 Logging
111 os module
118 Mixins
120 ArcPy
126 Arrays
132 2to3 tool
135 Unicode
138 Neo4j
140 Curses
141 Templates
145 heapq
146 tkinter
154 Audio
155 pyglet
157 ijson
160 Flask
161 Groupby
163 pygame
165 hashlib
166 Gzip
167 ctypes
185 pyaudio
186 shelve