Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Why I can not convert map object to list [duplicate]

I am having trouble in converting map to list, when it can be converted to set

list_nums_2 = [2, 4, 5, 9, 8, 7, 6, 3, 1, 0]
evens = filter(lambda a: a % 2 == 0, list_nums_2)
print(set(evens))  # Out: {0, 2, 4, 6, 8}
print(list(evens)) # Out: []

I know it's not because it's converted to set already as from below it is clear that set can be converted to list

set_1 = {2, 3, 4, 5, 6}

print(list(set_1))  # Out: [2, 3, 4, 5, 6]
like image 318
M_S_N Avatar asked Jan 27 '23 18:01

M_S_N


1 Answers

When you ran set(evens) it consumed all of the items in the filter object. Therefore, there are no items available when you execute list(evens) and an empty list is returned.

The filter object is an iterator, which is iterable so you can call next() on it to get the next item:

>>> evens = filter(lambda a: a % 2 == 0, list_nums_2)
>>> evens
<filter object at 0x7f2f4c309710>
>>> next(evens)
2
>>> next(evens)
4
>>> next(evens)
8
>>> next(evens)
6
>>> next(evens)
0
>>> next(evens)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration
>>> 

The exception is because there are no more items in the filter object.

like image 57
mhawke Avatar answered Feb 14 '23 02:02

mhawke