In this chapter, we take a close look at all the Python data types. Python provides us several native data types to store and process data. We make a distinction between basic types and the more advanced data structures.
Table of contents
Basic and advanced data types
The basic data types in Python store a single value, like a number or a piece of text. The basic data types in Python are:
Next, we have the more advanced Python data types. They can store many items, like lists or key-value pairs:
Mutability in Python
Data types can be categorized into two classes: mutable and immutable. An object is mutable if we can change the data it holds, and it’s immutable if we can’t change it. Examples of immutable data types in Python are:
- All numbers (integers, floats, complex numbers)
Python data types that are mutable are:
Why are these data types mutable? We didn’t dive into all these types yet, but let’s take a list as an example. Without knowing the exact details, I can tell you that you can add more items to a list, remove items, and replace them. These are not surprising features for a list, right? So a list can be changed, hence it is mutable.
However, an integer is simply a number, like 2, 3, and 4 are numbers. You can’t change a number; it is what it is. I can almost hear you thinking now. “But I can change a variable, even if it’s an integer!” You’re right, but that’s something different though.
Let’s look at an example were we assign the integer 2 to a variable called
myint, and then change it:
>>> myint = 2 >>> myint = 3
What we are doing, is reassigning a new value to a variable. We’re not changing the data, the number 2, itself.
There’s another way to explain this. Maybe you are familiar with pointers? A variable points to a spot in your computer’s memory. That is what we call a pointer. In the first instance,
myint points to a spot in memory where we stored the number 2. After changing
myint to 3, it points to another spot in memory where we store the number 3.
This is different from a list, for example. If the variable
mylist points to a list structure in memory, and we change that list, it still points to the same list structure. Python doesn’t replace the list but modifies it instead.
How to check the Python data type?
There’s a built-in function called
type which you can use to check data types in Python. Let’s look at some examples of
type at work:
>>> type(3) <class 'int'> >>> type('hello') <class 'str'> >>> type([1,2,3]) <class 'list'>
If you are experimenting in the REPL,
type is a valuable function that can give you more insight into what’s happening under the hood!