0

Here's some sample code. All I am trying to do is test the presence of an item inside a list. The list is created using the map function. The results change is I print the list first. Any ideas why this is happening?

In [20]: def f1():
    ...:     l = map(lambda x: x+'_1', ['a', 'b', 'c'])
    ...:     if 'a_1' in l:
    ...:         return True
    ...:     else:
    ...:         return False
    ...:
    ...:

In [21]: def f2():
    ...:     l = map(lambda x: x+'_1', ['a', 'b', 'c'])
    ...:     print(list(l))
    ...:     if 'a_1' in l:
    ...:         return True
    ...:     else:
    ...:         return False
    ...:
    ...:

In [22]: f1()
Out[22]: True

In [23]: f2()
['a_1', 'b_1', 'c_1']
Out[23]: False
  • That's interesting, I tested it and found that `print(l)` instead of `print(list(l))` yields the expected behavior. – Thomas Schillaci Mar 12 '20 at 08:23
  • 1
    FWIW: `return 'a_1' in l`… Having an `if ...: return True else: return False` is always superfluous. (This is unrelated to the issue though.) – deceze Mar 12 '20 at 08:24

1 Answers1

0

When you do:

print(list(l))

The cast from map to list emtpies your map, try calling print(list(l)) twice and you'll see what I mean.

Thomas Schillaci
  • 2,348
  • 1
  • 7
  • 19