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)returnsTruewhenvaluehas that type.>
isinstance(10, int)Result:
True
>
isinstance("Hello", int)Result:
False
>
isinstance("Hello", str)Result:
True
Remember, floats and integers are not the same type of value.
10.5is afloat, not anint.>
isinstance(10.5, int)Result:
False
>
isinstance(10.5, float)Result:
True
>
isinstance((1, 2), tuple)Result:
True
>
isinstance([1, 2], tuple)Result:
False
Here's our mixed list example again. Now we can use
isinstanceto decide which list elements to sum.>
donation_amounts = [400, "Amir", 200, None, 100, "Keanu"]donation_total = 0for donation in donation_amounts:if isinstance(donation, int):donation_total += donationdonation_totalResult:
700
What if we want to ask "is this either an
intor afloat?" We could writeisinstance(value, int) or isinstance(value, float). There's also a shorter way: we can pass multiple types in a tuple, likeisinstance(value, (int, float)). This means "isvalueany of these types?">
isinstance(4.5, (int, float))Result:
True
>
isinstance("4.5", (int, float))Result:
False
>
isinstance((3, 4.5), (int, float))Result:
False
>
isinstance((3, 4.5), (tuple, list))Result:
True
Here's a code problem:
Write a
string_countfunction to count how many of a list's elements are strings (thestrtype).def string_count(the_list):count = 0for value in the_list:if isinstance(value, str):count += 1return countassert string_count([None, 1, 3]) == 0assert string_count(["flavor", 23, "strawberry"]) == 2assert string_count(["Amir", 32, "Betty", 10, ["Cindy", 4]]) == 2- Goal:
No errors.
- Yours:
No errors.