Upgrade to Pro — share decks privately, control downloads, hide ads and more …

The Filter Function

The Filter Function

Basic understanding of the `filter` function.

Eloy Zuniga Jr.

May 15, 2018
Tweet

More Decks by Eloy Zuniga Jr.

Other Decks in Programming

Transcript

  1. Handle Nonetype objects # Remove Nonetypes before using Max L

    = [None, None, None] max([i for i in L if is not None], default=None) @eloy · python 3.6 · 2018 1/14
  2. Using the filter function # Remove Nonetypes before using Max

    max(filter(None, L), default=None) @eloy · python 3.6 · 2018 2/14
  3. Filter function # Takes a function and an iterable filter(<function>,

    <iterable>) @eloy · python 3.6 · 2018 4/14
  4. Let's try an example # Anything greater than 2 shall

    pass def greater_than_2(item): """Assume item is integer.""" return item > 2 items = filter(greater_than_2, [1, 2, 3, 4]) @eloy · python 3.6 · 2018 5/14
  5. Using the filter function # Remove Nonetypes before using Max

    max(filter(None, L), default=None) @eloy · python 3.6 · 2018 6/14
  6. Identity function # If NO function is passed, then we

    use the "Identity function" filter(None, iterable) # Identity function = Is this Truthy or Falsey? truthy_items = [True, object, 'a', '0', 1, 2, -1] falsey_items = [False, None, '', "", 0] @eloy · python 3.6 · 2018 8/14
  7. Testing identity function # Everything makes it through the filter

    everything = filter(None, [True, object, 'a', 1]) # Nothing makes it through the filter nothing = filter(None, [False, None, '', "", 0]) @eloy · python 3.6 · 2018 9/14
  8. Lets make a None function # Anything greater than 2

    shall pass def fake_none(item): """Test truthiness.""" return bool(item) items = filter(fake_none, [1, 2, 3, 4]) @eloy · python 3.6 · 2018 10/14
  9. Do you know the difference? 4 iterable 4 lazy iterable

    4 iterator 4 range We'll talk about this next month :D @eloy · python 3.6 · 2018 14/14