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


for example, want print out board tic tac toe initially

board = [[0]*3]*3 

i want use map apply print() each row, output is

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

in python 3, map returns iterator instead of list, example of adapting found

list(map(print, board)) 

which gives correct output. don't know what's going on here - can explain happening when do

list(iterator) 

?

the built-in list constructor common way of forcing iterators , generators iterate in python. when call map, returns map object instead of evaluating mapping, not desired author of code snippet.

however, using map print items of iterable on separate lines inelegant when consider power print function holds in python 3:

>>> board = [[0]*3]*3 >>> board[0] board[1] true >>> "uh oh, don't want that!" "uh oh, don't want that!" >>> board = [[0]*3 _ in range(3)] >>> board[0] board[1] false >>> "that's lot better!" "that's lot better!" >>> print(*board, sep='\n') [0, 0, 0] [0, 0, 0] [0, 0, 0] 

additional note: in python 2, print treated statement, , not powerful, still have @ least 2 better options using map:

  1. use old for-loop:

for row in board: print row

  1. import python 3's print function __future__ module:

from __future__ import print_function


Popular posts from this blog

c# - ODP.NET Oracle.ManagedDataAccess causes ORA-12537 network session end of file -

matlab - Compression and Decompression of ECG Signal using HUFFMAN ALGORITHM -

utf 8 - split utf-8 string into bytes in python -