1

I'm just trying to figure out what is happening in this python code. I was trying to use this answer here, and so I was tinkering with the console and my list elements just vanished.

What I was doing was loading the lines into a file into a list, then trying to remove the newline chars from each element by using the lambda thing from the other answer.

Can anyone help me explain why the list became empty?

>>> ================================ RESTART ================================
>>> x = ['a\n','b\n','c\n']
>>> x
['a\n', 'b\n', 'c\n']
>>> x = map(lambda s: s.strip(), x)
>>> x
<map object at 0x00000000035901D0>
>>> y = x
>>> y
<map object at 0x00000000035901D0>
>>> x
<map object at 0x00000000035901D0>
>>> list(x)
['a', 'b', 'c']
>>> x = list(x)
>>> x
[]
>>> y
<map object at 0x00000000035901D0>
>>> list(y)
[]
>>> 
Community
  • 1
  • 1
r12
  • 1,712
  • 1
  • 15
  • 25

1 Answers1

1

You are using Python3, so map returns a mapobject. You can only iterate over a mapobject once. So convert it to a list if you need to iterate over the items more than once. (also if you need to look up by index etc.)

Use

x = list(map(lambda s: s.strip(), x))

or better - a list comprehension

x = [s.strip() for s in x]
John La Rooy
  • 295,403
  • 53
  • 369
  • 502