-1

join on map object with Python 3.5.2 IDE

Is join should not be used for map objects?

Is join should not be used for list created by map?

Python 3.5.2 (v3.5.2:4def2a2901a5, Jun 25 2016, 22:01:18) [MSC v.1900 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> a = map(lambda x:x[1], [('11', '22'), ('22', '33'), ('33', '44')])
>>> list(a)
['22', '33', '44']
>>> '.'.join(a)
''
>>> ''.join(list(a))
''
>>> ''.join(['22', '33', '44'])
'223344'
>>> 
Seong
  • 51
  • 5

1 Answers1

2

The list(a) consumes the items from the map object. So when you subsequently try to access those items again, e.g. with '.'.join(a) the map object is empty. That's why join returns an empty string.

You can call join() on a map:

>>> a = map(lambda x:x[1], [('11', '22'), ('22', '33'), ('33', '44')])
>>> '.'.join(a)
'22.33.44'
>>> '.'.join(a)
''

but once it's consumed that's it, so the second join() doesn't work as you might expect.

You can instead bind the result of list(a) to a variable and then use that again later:

>>> a = map(lambda x:x[1], [('11', '22'), ('22', '33'), ('33', '44')])
>>> l = list(a)
['22', '33', '44']
>>> '.'.join(l)
'22.33.44'
mhawke
  • 84,695
  • 9
  • 117
  • 138