3
l=['Python', 3, 2, 4, 5, 'version']
l=filter(lambda x:type(x)==int,l)
print(list(l))
print(max(l))

getting this error but i don't know why.. ValueError: max() arg is an empty sequence

if I am not printing list(l) it will work..

l=['Python', 3, 2, 4, 5, 'version']
l=filter(lambda x:type(x)==int,l)
print(max(l))

output: 5

after printing the list of the filter object it won't work and i don't know why can you help me? any fix?

Ori
  • 67
  • 5
  • I'd assume that `list(l)` consumes the sequence, leaving `l` as an iterator past the end of the sequence – UnholySheep Jan 15 '21 at 15:05
  • 2
    In Python 2, `filter` was a function that returned a list. In Python 3, it is a class whose instances are iterators. – chepner Jan 15 '21 at 15:07

1 Answers1

6

filter returns an iterator. After calling list(l), the iterator is exhausted, and thus you can't draw any more values from it.

You can try this and see:

l = ['Python', 3, 2, 4, 5, 'version']
l = filter(lambda x: type(x) == int, l)
print(list(l))
print(list(l))

And the second print statement gives the empty list:

[3, 2, 4, 5]
[]

This would work:

l = ['Python', 3, 2, 4, 5, 'version']
l = filter(lambda x: type(x) == int, l)
l = list(l)
print(l)
print(max(l))
chepner
  • 497,756
  • 71
  • 530
  • 681
kwkt
  • 1,058
  • 3
  • 10
  • 19
  • 1
    See https://stackoverflow.com/questions/2776829/difference-between-pythons-generators-and-iterators – mkrieger1 Jan 15 '21 at 15:08
  • Thanks @chepner for the edit! I definitely missed that. – kwkt Jan 15 '21 at 15:08
  • 1
    `generator` is a specific class, instances of which are defined using generator expressions or generator functions. Iterator is the term for anything that implements `__next__`, allowing you to retrieve an argument via the `next` function. As far as I know, you could use "generator" as a synonym for "iterator", but I think it's clearer to avoid the ambiguity. – chepner Jan 15 '21 at 15:09