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

The `max` function

The `max` function

Using the `max` function in python 3.6. Some caveats to watch out for.

Eloy Zuniga Jr.

April 17, 2018
Tweet

More Decks by Eloy Zuniga Jr.

Other Decks in Programming

Transcript

  1. Max function # Assume `L` is a list of datetimes,

    Nonetypes L = get_dates() max(L) # returns biggest item @eloy · python 3.6 · 2018 2/11
  2. Empty sequence # Can we get a max item from

    an empty sequence? max([]) @eloy · python 3.6 · 2018 4/11
  3. Handle TypeError # Lets handle the `TypeError` try: max([]) except

    TypeError: pass # Lets write less and make it more readable max([], default=None) @eloy · python 3.6 · 2018 5/11
  4. None list # Can we get a max item from

    a list of Nonetypes? L = [None, None] max(L) @eloy · python 3.6 · 2018 6/11
  5. Handle ValueError # Lets handle the `ValueError` L = [None,

    None] try: max(L) except ValueError: pass # What if `L` had both datetimes and Nonetype values? L = L + get_dates() @eloy · python 3.6 · 2018 7/11
  6. Remove None items # Remove Nonetypes before using Max max([i

    for i in L if is not None]) @eloy · python 3.6 · 2018 8/11
  7. Does this work? # Remove Nonetypes before using Max L

    = [None, None, None] max([i for i in L if is not None]) @eloy · python 3.6 · 2018 9/11
  8. With default param # 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 10/11