![]() ![]() For each number, we check if it's divisible by 2. When provided with a lambda - the number is an element of the iterable we're currently filtering. This condition can be supplied either as an anonymous function - lambda or a standalone function: number_list = įiltered_list = list( filter( lambda number: number % 2 = 0, number_list)) If the condition isn't satisfied and False is returned, the element of the iterable is filtered out. ![]() If the condition is satisfied and True is returned, it's not filtered out. If we were to do filtering via for and if statements, it'd look something like: # Create a simple list numbered 0 to 10īy contrast, we could've achieved this same result using filter(), and passing in the same condition. Since filter() returns a generator ( filter object) - we'll wrap it in a list() to convert it back to a simple list. The filter() Functionįilter() is a built-in function, and it allows us to take a group of iterable items and test if the elements within the iterable meet your specified filter criteria: filter(function, iterable) Iteration tools offer efficient, standardized functions (similar to the functions you'd see in functional programming languages like Haskell) that integrate with other iterative functions to simplify iterative tasks down to just a few lines of code. We often ignore the features and tools a language may have that can help us with iterative tasks. Typically, when we work with iterable objects, we loop through them using basic tools like for loops. We'll start by defining iterable objects and iteration functions and then proceed to look at some examples of the four iteration functions mentioned above. The first item in both iterables is paired, the second item in both iterables is paired together, and so on.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |