1

I have this list:

list1 = [1, 1, 1, 3, 3, 3, 56, 6, 6, 6, 7]

And I wat to get rid of duplicate values. The code for the map function is taken from here. this is the complete testing code:

list1 = [1, 1, 1, 3, 3, 3, 56, 6, 6, 6, 7]

list2 = []
map(lambda x: not x in list2 and list2.append(x), list1)
print(list2)

list2 = []
[list2.append(c) for c in list1 if c not in list2]
print(list2)

list2 = []

for c in list1:
    if c not in list2:
        list2.append(c)

print(list2)

In Python 2.7 is prints:

[1, 3, 56, 6, 7]
[1, 3, 56, 6, 7]
[1, 3, 56, 6, 7]

In Python 3.4 it prints:

[]
[1, 3, 56, 6, 7]
[1, 3, 56, 6, 7]

Why the map function returns an empty list in Python3?

Community
  • 1
  • 1
Broken_Window
  • 2,037
  • 3
  • 21
  • 47

1 Answers1

2

Because in a map is not evaluate immediately. It works as a generator where elements are generated on the fly by need: this can be more efficient since it is possible you for instance only need the first three elements so why would you calculate all elements? So as long as you do not materialize the output of map in a way, you have not really calculated the map.

You can for instance use list(..) to force Python to evaluate the list:

list(map(lambda x: not x in list2 and list2.append(x), list1))

In that case will generate the same result for list2.

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555