Why does this Python behavior behave differently for map and without map

Why do these two print statements produce different results when the two casts from int to string look the same? What am I missing?

Pay

is a list of integers

#ex.1
print ' '.join(map(str, board[:3]))
#ex.2
print ' '.join(str(board[:3]))

#out.1
0 1 2
#out.2
[ 0 ,   1 ,   2 ]

      

+3


source to share


2 answers


print(" ".join(map(str, board[:3])))

      

maps each element sliced board

into a literal integer and concatenates it with spaces (maybe what you want and need to do)



print(' '.join(str(board[:3])))

      

converts list

as its representation (with parentheses and all) and then inserts a space between each character. Not what you want.

+3


source


See exactly what is going on in your code:

First case:

In [4]: map(str,boards[:3])
Out[4]: ['0', '1', '2']

In [5]: ''.join(map(str,boards[:3]))
Out[5]: '012'

      

Convert all the elements in a list to string format and when you use join

it will connect to those elements.



Second case:

In [6]: str(boards[:3])
Out[6]: '[0, 1, 2]'

In [7]: ''.join(str(boards[:3]))
Out[7]: '[0, 1, 2]'

      

First the whole list is converted as a list and when using string concatenation it will give the same.

+1


source







All Articles