imap vs map

mk mrkafk at
Fri Mar 5 20:55:14 CET 2010

Hello everyone,

I re-wrote more "slowly" an example at the end of

This example finds anagrams in the text file.

from itertools import groupby, imap
from operator import itemgetter

from string import ascii_lowercase, ascii_uppercase, punctuation, 
maketrans, translate

data = open(r"c:\temp\words.txt", "rt").read()

trtable = maketrans(ascii_uppercase, ascii_lowercase)

words = translate(data, trtable, deletions = punctuation)

words = list(set(words.split()))

sw = sorted(words, key=sorted)

gb = groupby(sw, sorted)

print map(list, imap(itemgetter(1), gb))

Word Aligned
space sensitive programming
Feed Logo tins
Essential Python post  Reading List
stop course there
times isnt

Now, when I execute above, it works:

[['capes', 'space'], ['aligned'], ['reading'], ['essential'], 
['programming'], ['course'], ['feed'], ['word'], ['there', 'three'], 
['sensitive'], ['times'], ['logo'], ['python'], ['list'], ['isnt', 
'tins'], ['stop', 'post']]

However, when I change the last line to:

print map(list, map(itemgetter(1), gb))

It stops working:

[[], [], [], [], [], [], [], [], [], [], [], [], [], [], [], ['post']]

Why? I was under impression that the only difference between map and 
imap is that imap returns iterator allowing to produce a list, while map 
returns equivalent list?


More information about the Python-list mailing list