1

For example, I want to print out a board for tic tac toe that is initially

board = [[0]*3]*3

I want to use map to apply print() to each row, so that the output is

[0, 0, 0]
[0, 0, 0]
[0, 0, 0]

In Python 3, map returns an iterator instead of a list, so an example of adapting to this I found is

list(map(print, board))

Which gives the correct output. But I don't know what's going on here - can someone explain what is happening when you do

list(iterator)

?

mango
  • 1,183
  • 6
  • 17
  • 33
  • 5
    **Don't do this.** Use a loop. `map` is for applying a transformation to data, not for causing side effects. – user2357112 Apr 23 '15 at 04:36
  • 5
    Also, `[[0]*3]*3` is the wrong way to initialize that board. All the sublists in that board are the same list; it'll break as soon as you try to do anything with it, such as `board[0][0] = 1`. Use a list comprehension: `board = [[0]*3 for i in xrange(3)]` – user2357112 Apr 23 '15 at 04:38

2 Answers2

4

The built-in list constructor is a common way of forcing iterators and generators to fully iterate in Python. When you call map, it only returns a map object instead of actually evaluating the mapping, which is not desired by the author of your code snippet.

However, using map just to print all the items of an iterable on separate lines is inelegant when you consider all the power that the print function itself holds in Python 3:

>>> board = [[0]*3]*3
>>> board[0] is board[1]
True
>>> "Uh oh, we don't want that!"
"Uh oh, we don't want that!"
>>> board = [[0]*3 for _ in range(3)]
>>> board[0] is board[1]
False
>>> "That's a lot better!"
"That's a lot better!"
>>> print(*board, sep='\n')
[0, 0, 0]
[0, 0, 0]
[0, 0, 0]

Additional Note: In Python 2, where print is treated as a statement, and is not so powerful, you still have at least two better options than using map:

  1. Use a good old for-loop:

for row in board: print row

  1. Import Python 3's print function from the __future__ module:

from __future__ import print_function

Shashank
  • 13,713
  • 5
  • 37
  • 63
2
>>> list(map(print, board))
[0, 0, 0]
[0, 0, 0]
[0, 0, 0]
[None, None, None]

When you call list on an iterable, it extracts each element from the iterable. In this case, a side-effect of that is that the three rows are printed. The result of the print operation, though, is None. Thus, for each print performed, a None is added to the list. The last row above, consisting of the three Nones, is the actual list that was returned by list.

John1024
  • 109,961
  • 14
  • 137
  • 171