elenhil elenhil -3 years ago 151
Python Question

Python: list(filter object) empties the object


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

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
it somehow rewrites
filter object instead of just returning the list interpretation

Is it an OK behavior? It doesn't look for me it is

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download