As mentioned in this article, Python is a dynamically-typed language, meaning the type of a variable is determined during program execution and cannot be changed afterward. However, this does not mean that there are no distinctions between the various variable types.
Let’s take a look at the data types natively present in Python:
- Strings:
str
- Numbers:
int
,float
,complex
- Sequences:
list
,tuple
- Mappings:
dict
- Sets:
set
,frozenset
- Boolean:
bool
- Binary:
bytes
,bytearray
,memoryview
In Python, it is not necessary to specify the type of a variable when declaring it. This allows a variable to hold any of the types listed above. Moreover, dynamic typing means that a variable’s type can change at any time during code execution.
For more details on Python data types, we encourage you to check the official documentation.
Setting the Data Type
Here are some examples of how to assign different data types to a variable:
- String:
x = "Hello World"
- Number:
- Int:
x = 1
- Float:
x = 1.0
- Complex:
x = 1j
- Int:
- Sequences:
- List:
x = ["Monday", "Tuesday", ...]
- Tuple:
x = ("Monday", "Tuesday", ...)
- List:
- Mappings:
x = {"key": "value", "key": "value", ...}
- Sets:
- Set:
x = {"Monday", "Tuesday", ...}
- FrozenSet:
x = frozenset({"Monday", "Tuesday", ...})
- Set:
- Boolean:
x = True
orx = False
- Binary:
x = b"Hello World"
Sequences Vs. Sets
Since sequences and sets might seem similar at first glance, let’s outline the main differences between these two data types:
- List: Lists can hold heterogeneous data, allow duplicates, and are mutable. A list can be initialized with
x = list()
orx = []
. - Tuple: Tuples can hold heterogeneous data, allow duplicates, and are immutable. A tuple can be initialized with
x = tuple()
orx = ()
. - Set: Sets can hold heterogeneous data, do not allow duplicates, and are mutable. A set can be initialized with
x = set()
.- There is also an immutable version that can be initialized with
x = frozenset()
.
- There is also an immutable version that can be initialized with
- Mappings: A mapping can hold heterogeneous data, does not allow duplicate keys, and is mutable. A mapping can be initialized with
x = dict()
orx = {}
.
Conclusion
We’ve covered an overview of the main data types in Python. In the upcoming articles, we will explore practical applications to help you better understand their use and nuances. Stay tuned to continue enhancing your Python skills!