stackoverflow.com/questions/23684999/python-filter-function
1 Users
0 Comments
2 Highlights
0 Notes
Tags
Top Highlights
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?
Python filter() function Ask Question Asked 8 years, 9 months ago Modified 3 years, 3 months ago Viewed 4k times 4 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? pythoninputfilter Share Improve this question Follow edited May 15, 2014 at 17:38 DanGar 2,9881717 silver badges1717 bronze badges asked May 15, 2014 at 17:30 nsamuel 10511 silver badge1111 bronze badges xrange(), generators etc – Ashwini Chaudhary May 15, 2014 at 17:32 Add a comment 2 Answers Sorted by: 5 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] Share Improve this answer Follow edited Oct 10, 2015 at 8:43 answered May 15, 2014 at 17:34 anon582847382 19.5k55 gold badges5353 silver badges5757 bronze badges 1 Not entirely. filter(lambda x: x%2, {1,2,3,4,5}) gives back a list because sets are not sequences. Similarly for dicts. – roippi May 15, 2014 at 17:40 @roippi I wasn't aware of that, thank you very much. I have updated the answer. – anon582847382 May 15, 2014 at 17:43 1 For python3, it has changed. – shaik moeed Nov 19, 2019 at 6:53 Add a comment 3 For python 3, the definition is changed. From doc filter(function, iterable) Construct an iterator from those elements of iterable for which function returns true. iterable may be either a sequence, a container which supports iteration, or an iterator. If function is None, the identity function is assumed, that is, all elements of iterable that are false are removed. Example: >>> filter(lambda x: x in 'hello buddy!', 'hello world') <filter object at 0x000002ACBEEDCB00> # filter returns object !important >>> ''.join([i for i in filter(lambda x: x in 'hello buddy!', 'hello world')]) 'hello old' >>> [i for i in filter(lambda n: n % 2, {0, 1, 2, 3, 4, 5, 6, 7, 8, 9})]
Glasp is a social web highlighter that people can highlight and organize quotes and thoughts from the web, and access other like-minded people’s learning.