Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python filter() function

filter(function,  an_iter)
*If the iterable an_iter is a sequence, then the returned value is of that same type, 
otherwise the returned value is a list.* 

I came across the above description as part of the definition for the filter(func, a_sequence) function in Python.

I understand how filter works on a sequence type (lists, strings, tuples). However, can you give me situations where a non-sequence type is the an_iter parameter and what kind of result would form?

like image 654
nsamuel Avatar asked Oct 27 '25 21:10

nsamuel


1 Answers

When it says 'non-sequence', it basically means generators or unordered iterables. Here is an example with xrange:

>>> filter(lambda n: n % 2, xrange(10))
[1, 3, 5, 7, 9]

And with a set:

>>> filter(lambda n: n % 2, {0, 1, 2, 3, 4, 5, 6, 7, 8, 9})
[1, 3, 5, 7, 9]
like image 109
anon582847382 Avatar answered Oct 29 '25 11:10

anon582847382



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!