Python for Programmers: Type
Welcome to the Type lesson!
This lesson is shown as static text below. However, it's designed to be used interactively. Click the button below to start!
A previous lesson showed the
isinstancefunction. We checked values' types by passingint,str,tuple, etc. asisinstance's second argument.>
isinstance(100, int)Result:
True
We've also used
int,str, andtupleas functions. They convert values into integers, strings, and tuples.>
int("100")Result:
100
>
isinstance("100", int)Result:
False
>
isinstance(int("100"), int)Result:
True
int,str,tuple, etc. aren't special syntax in Python. They're values that we can pass toisinstanceas regular function arguments. So what are these values?We can think of
intas representing the idea of "integerness" andstras representing the idea of "stringness". Likewise fortuple,list,dict, and many others. We'll refer to them as "type objects" or simply "types".It's very useful to have a value that represents "stringness" or "listness". It binds a lot of ideas together, as we already saw above: we can use the same value to ask "is this an integer?" and to convert other data types into integers.
Sometimes we have a value and want to get its type object. The built-in
typefunction does that:type(0)gives usint.(When a code example returns the
inttype object, you can answer withint, without any quotes around it. They're not strings; they're type objects!)>
type(10)Result:
int
Note that if you try
type(10)in an interactive Python shell, you may see a different result. Different environments print type objects differently. But it's still the same type object! It's like the difference between"Amir"and'Amir': they're two different ways to print the same value.Now we've seen two closely-related tools:
typeasks "what is the type of this value?" andisinstanceasks "is this a value of this type?"We've also seen that type objects like
intare regular Python values. That means that we can store them inside variables. Then we can pass those variables to functions likeisinstance.>
some_type = type(0)# `some_type` holds `int` here!isinstance(0, some_type)Result:
True
>
some_type = type(0)isinstance(77, some_type)Result:
True
>
some_type = type("some string")isinstance("a different string", some_type)Result:
True
>
some_type = type("some string")isinstance(77, some_type)Result:
False
Here's a quick rundown of common Python type objects:
- Booleans are
bools. - Integers are
ints. - Floating point numbers are
floats. - Strings are
strs. - Lists are
lists. - Tuples are
tuples. - Dictionaries are
dicts.
- Booleans are
>
type(True)Result:
bool
>
type("Welcome")Result:
str
>
type([1, 2, None])Result:
list
>
type(2.5)Result:
float
>
type((1, 2, 3))Result:
tuple
All type objects work with
isinstance, all of them can be returned bytype, and all of them convert values when called as functions.