mango
mango

Reputation: 1233

What is happening in Python 3 when I call list() on an iterator?

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)

?

Upvotes: 1

Views: 98

Answers (2)

Shashank
Shashank

Reputation: 13869

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

Upvotes: 4

John1024
John1024

Reputation: 113994

>>> 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.

Upvotes: 2

Related Questions