Execute Program

Python for Programmers: Isinstance

Welcome to the Isinstance lesson!

This lesson is shown as static text below. However, it's designed to be used interactively. Click the button below to start!

  • Suppose that we have a mixed list of integers and strings. We want to sum up all of the integers in the list, ignoring the strings.

  • >
    donation_amounts = [400, "Amir", 200, None, 100, "Keanu"]
  • Ideally we'd avoid messy data like this. But sometimes it's unavoidable due to constraints outside of our control. For example, the data might come from another company's API, or from a public data source like a government.

  • To get the sum, we'll examine each list element and ask Python: "is this an int?" Python has a way to do this: isinstance(value, some_type) returns True when value has that type.

  • >
    isinstance(10, int)
    Result:
    TruePass Icon
  • >
    isinstance("Hello", int)
    Result:
    FalsePass Icon
  • >
    isinstance("Hello", str)
    Result:
    TruePass Icon
  • Remember, floats and integers are not the same type of value. 10.5 is a float, not an int.

  • >
    isinstance(10.5, int)
    Result:
    FalsePass Icon
  • >
    isinstance(10.5, float)
    Result:
    TruePass Icon
  • >
    isinstance((1, 2), tuple)
    Result:
    TruePass Icon
  • >
    isinstance([1, 2], tuple)
    Result:
    FalsePass Icon
  • Here's our mixed list example again. Now we can use isinstance to decide which list elements to sum.

  • >
    donation_amounts = [400, "Amir", 200, None, 100, "Keanu"]

    donation_total = 0
    for donation in donation_amounts:
    if isinstance(donation, int):
    donation_total += donation
    donation_total
    Result:
    700Pass Icon
  • What if we want to ask "is this either an int or a float?" We could write isinstance(value, int) or isinstance(value, float). There's also a shorter way: we can pass multiple types in a tuple, like isinstance(value, (int, float)). This means "is value any of these types?"

  • >
    isinstance(4.5, (int, float))
    Result:
    TruePass Icon
  • >
    isinstance("4.5", (int, float))
    Result:
    FalsePass Icon
  • >
    isinstance((3, 4.5), (int, float))
    Result:
    FalsePass Icon
  • >
    isinstance((3, 4.5), (tuple, list))
    Result:
    TruePass Icon
  • Here's a code problem:

    Write a string_count function to count how many of a list's elements are strings (the str type).

    def string_count(the_list):
    count = 0
    for value in the_list:
    if isinstance(value, str):
    count += 1
    return count
    assert string_count([None, 1, 3]) == 0
    assert string_count(["flavor", 23, "strawberry"]) == 2
    assert string_count(["Amir", 32, "Betty", 10, ["Cindy", 4]]) == 2
    Goal:
    No errors.
    Yours:
    No errors.Pass Icon