Python Data Types
What you will learn
- What a data type is and why Python needs it
- The main built-in types:
int,float,str,bool,NoneType - A first look at the collection types:
list,tuple,dict,set - How to check a type with
type()andisinstance() - Why mixing types can cause an error
1. What is a data type?
Every value in Python has a type. The type says what kind of thing the value is and what you can do with it.
| Value | Type | What it is |
|---|---|---|
42 |
int |
a whole number |
3.14 |
float |
a number with a decimal point |
"hi" |
str |
text (a string) |
True |
bool |
true or false (a boolean) |
None |
NoneType |
"no value" |
You can ask Python for the type of any value with type():
print(type(42), type(3.14), type("hi"), type(True), type(None))
Output:
<class 'int'> <class 'float'> <class 'str'> <class 'bool'> <class 'NoneType'>
The word class is how Python writes the word type. You can ignore it for now: <class 'int'> means "the type int".
Quick check: what is the type of `"42"` (with quotation marks)?
str. The quotation marks make it text, not a number.
2. The type belongs to the value
In Python, a value has a type; the variable is only a name for it (lesson 2.1). So the same name can point to different types over time:
x = 5
print(type(x))
x = "five"
print(type(x))
Output:
<class 'int'>
<class 'str'>
Python looks at the value when it runs the code. This style is called dynamic typing. It is flexible, but it means you must keep track of what your names hold.
3. The type decides what operators do
The same symbol can do different things for different types:
| Code | Result | Why |
|---|---|---|
3 + 4 |
7 |
adds numbers |
"3" + "4" |
34 |
joins text |
"3" * 3 |
333 |
repeats text |
1 + 2.5 |
3.5 |
an int and a float give a float |
print("3" + "4")
print(3 + 4)
print("3" * 3)
print(1 + 2.5, type(1 + 2.5))
Output:
34
7
333
3.5 <class 'float'>
4. Mixing types: errors
Python does not guess what you mean when you combine types that do not fit together:
print("Age: " + 25)
TypeError: can only concatenate str (not "int") to str
print(3 + "4")
TypeError: unsupported operand type(s) for +: 'int' and 'str'
A TypeError means the type was wrong for that operation. The fix is to make the types match: turn the number into text with str(25), or put the number in an f-string (lesson 1.2): f"Age: {25}". Converting types is covered in lesson 2.4.
The same happens with functions. len counts items, and it cannot work on a plain number:
print(len("hello"), len([1, 2, 3]))
print(len(5))
5 3
TypeError: object of type 'int' has no len()
5. A first look at collections
Some types hold several values in one. You will study each in its own chapter:
| Type | Example | Chapter |
|---|---|---|
list |
[1, 2] |
7 |
tuple |
(1, 2) |
8 |
dict |
{"a": 1} |
9 |
set |
{1, 2} |
10 |
print(type([1, 2]), type((1, 2)), type({"a": 1}), type({1, 2}))
<class 'list'> <class 'tuple'> <class 'dict'> <class 'set'>
6. Checking a type: type() and isinstance()
type(x) tells you the type. To ask a yes or no question, use isinstance(value, type):
print(isinstance(5, int), isinstance(5, float), isinstance("a", str))
True False True
You can also compare directly, type(5) == int (which gives True). The professional habit is to prefer isinstance, because it also accepts values of related types. For example isinstance(True, int) is True, because a bool counts as a kind of int (lesson 2.3). You will use isinstance more in the chapters on classes and functions.
Worked example: find the type, then fix the error
Why does this fail? total = "10" + 5
| Step | What you do | Result |
|---|---|---|
| 1 | Find the types: "10" is text, 5 is a number |
str and int |
| 2 | Python cannot add text and a number | TypeError |
| 3 | Decide what you want: a number sum or joined text | |
| 4a | A number: convert the text, int("10") + 5 |
15 |
| 4b | Text: convert the number, "10" + str(5) |
"105" |
The right fix depends on what you meant. The error only tells you the types did not match.
Common mistakes
- Thinking
"5"and5are the same. One is text, the other a number:"5" + "5"gives"55", not10. - Forgetting that
input()returns text (lesson 2.5), then adding it to a number. - Reading
<class 'int'>as an error. It is just how Python writes the type. - Assuming a name keeps its type. A name can be pointed at a value of a different type later.
Key takeaways
- Every value has a type:
int,float,str,bool,NoneType, or a collection such aslist. - Check a type with
type(x), and ask a yes/no question withisinstance(x, int). - The type decides what an operator does:
+adds numbers but joins text. - Mixing incompatible types gives a
TypeError. Convert one side so that the types match.
Practice
1. What is the type of 7.0? And of "7.0"?
Show answer
float, then str. The quotation marks make the second one text.
2. What does print("ab" * 3) show?
Show answer
ababab. Multiplying text repeats it.
3. Why does "Total: " + 50 fail? Give two ways to fix it.
Show answer
It adds text and a number, which gives a TypeError. Fix it with "Total: " + str(50) or with an f-string, f"Total: {50}".
4. What does isinstance(3.5, int) give?
Show answer
False. 3.5 is a float.
5. After x = 10 and then x = "ten", what is type(x)?
Show answer
<class 'str'>. The name x now points to a string; the older number is gone from x.
6. Which type is each: [1, 2], (1, 2), {1, 2}, {"a": 1}?
Show answer
list, tuple, set and dict.