Search code examples
pythonlistfilterpython-3.6

Python: list(filter object) empties the object


guys!

I'm using Python 3.6.1 and got into an interesting issue:
I'm using a simple itertools.filter() to get a sub-list from an items list, and then I just print it twice.

items = [1,2,3,4,5]
operateVersions = filter(lambda t: t, items)
print ("1: %s" % list(operateVersions))
print ("2: %s" % list(operateVersions))

The result is weird:

1: [1, 2, 3, 4, 5]
2: []

so, when i run list(operateVersions) it somehow rewrites operateVersions filter object instead of just returning the list interpretation
Is it an OK behavior? It doesn't look for me it is


Solution

  • A filter is a special iterable object, and like a generator, you can only iterate over it once. So essentially it returns an empty list when you run it a second time.