Data Types are the core foundation to writing code in Python. Data Types are deeply linked to Python Variables, as one cannot exist without the other. Because of their connection to each other, these two elements are often confused, or seen as the same thing, when in fact they are slightly different
NOTE: This tutorial requires that Python is already installed, as well as an IDE (Integrated Development Environment), such as PyCharm. It’s also recommended that you have a basic understanding of How to Use Python if this is your first time learning Python.
With that said, let’s get started with this free Python Data Types tutorial.
What are Data Types in Python?
Python is an Object-Oriented Language, which means that it bundles related properties and behaviors into individual objects.
One of these are Variables which are containers for storing data values in Python. They allow Python to better understand our code and how it should execute it.
However, these items cannot become variables unless we assign them first, in order for Python to know what they are, and then what to do with them.
To do this we use Python Data Types.
There are numerous Data Types in Python, each with their own speciality, and function, which allow us to create compelling code in Python.
Think of Data Types as a labels or categories for variables, which defines them as follows:
- Integers (int) – Whole numbers such as: 1, 14, 576.
- Floating Point (float) – Decimal values such as: 1.24, 5.6 and Fractional Values such as 1/2, 9/6.
- Strings (str) – Sequence of Characters such as: “I love Python”, “this course is great”, “year 3000”.
- Booleans (bool) – Logical values representing: TRUE or FALSE.
- Lists (list) – Ordered sequence of Objects such as: [14,”welcome”,365.34]
- Dictionaries (dict) – Unordered Key:Value Pairs: {“amount” : “value” , “name” : “Susan”}
- Tuples (tuple) – Ordered immutable sequence of objects: (14,”welcome”,365.34)
- Sets (set) – Unordered Collection of Unique objects: {“set1”,”set2”}
- Frozen Sets (frozenset) – Immutable set: ({“apple”, “banana”, “orange”})
- Range (range) : x = range(5)
- Bytes (bytes) : x = b”Hello”
- Byte Array (bytearray) : x = bytearray(3)
- Memory View (memoryview) : memoryview
- Complex Numbers (j) – Stores Real or Imaginary Numbers
As you progress as a coder in other languages, you will see many of these Data Types reappear, especially int, float, string and bool, as they are practically in every coding language.
The above list are the most common Data Types you will find in Python, though there are a few more not listed that are also Data Types, albeit that they aren’t used as often.
To illustrate this, Python Data Types can be further categorized into 7 primitive categories as follows:
- Numeric Data Types (Python Numbers)
- Integers (int)
- Floating Point (float)
- Complex (j)
- Text Data Types
- Strings (str)
- Boolean Data Types
- Booleans (bool)
- Sequence Data Types
- Lists (list)
- Tuples (tuple)
- Range (range)
- Mapping Data Types
- Dictionaries (dict)
- Set Data Types
- Set (set)
- Frozen Set (frozenset)
- Binary Data Types
- Bytes (bytes)
- Byte Array (bytearray)
- Memory View (memoryview)
Here is a table of all Data Types, grouped into their following categories:
[INSERT TABLE]
Let’s take a brief look at each of these Data Types.
Numeric Data Types (Python Numbers)
The three main numbers in Python are Integers (int), Floating Point (float) and Complex Numbers (j).
Integer (int) Numbers in Python
Integers are a Python Data Type that can only be Whole Numbers, meaning that they cannot consist of any Fractions or Decimals.
Examples of Whole Numbers are:
- 0, 1, 5, 24, 627, 7725, 83476 etc.
We can Define a Variable to a Data Type, such as an integer (int) in Python, using the equals “=” sign.
For Example:
x = 5 # x is the Variable, 5 is the int Data Type
y = 627 # y is the Variable, 627 is the int Data Type
z = 83476 # z is the Variable, 83476 is the int Data Type
Floating Point (float) Numbers in Python
Floating Point numbers are a Python Data Type that can only be Decimals or Fractions, such as:
- 1.26, 47.5892, ½ , ⅖, 132/54 etc.
We define a Floating Point (float) as a Variable, in exactly the same way we do an Integer, by using the equals “=” sign.
Decimal Values
For example, let’s do a quick currency exchange rate from United States Dollar (USD) to Canadian Dollar (CAD), each with decimal values:
x = 1.26 # x is the Variable, 1.26 is the float Data Type
y = 47.5892 # y is the Variable, 47.5892 is the float Data Type
Fraction Values
Floating Points data types can also be fractions as follows:
x = 1/2 # x is the Variable, 1/2 is the float Data Type
y = 2/5 # x is the Variable, 1/5 is the float Data Type
z = 132/54 # x is the Variable, 132/54 is the float Data Type
Complex Numbers (j) in Python
Complex Numbers are a Python Data Type that consists of be Real Numbers (Whole, Rational & Irrational), as well as Imaginary Numbers, such as:
Whole Numbers
Whole Numbers consist of Non-Decimal and Non-Fraction Numbers
- 0
- 1
- 387
- 6584
- 86037
Rational Numbers
Rational Numbers CAN be written as a Ratio such as a simple fraction or Repeating Decimal Value
- 4/5
- 0.333…
- 1.5
Irrational Numbers
Irrational Numbers CANNOT be written as Ratio such as a Fraction or Repeating Decimal Value
- π (pi) = 3.1415926535897932384626433832795…
- √2 = 1.41421356237309…
- e (Euler) = 2.7182818284590452353602874713527…
- Φ (Golden Ratio) = 1.61803398874989484820…
- 22/7 = 3.1428571428571
We again define a Complex Number as a Variable, by using the equals “=” sign.
We do however append a literal number in the form of ”j” into the equation.
x = 5 + 3.75j # x is the Variable, 5 + 3.75j is the complex number Data Type
These three Numeric Python Data Types (integer, floating point & complex number) can be used in conjunction with Python Operators such as Arithmetic Operators, Assignment Operators, Comparison Operators and more, in order to create simple to complex equations and code in Python.
Text Data Types
There is only one Text Data Type in Python, which are Strings (str). Strings help us to output words and sentences in Python and code in general.
Strings (str) in Python
Strings in Python are surrounded by either single quotation marks ‘ ‘, or double quotation marks “ “.
We again assign the String Data Type to a Variable in order for it to function in Python.
x = “Python is Awesome”
Y = ‘Cats make great pets!’
Strings can contain most known special characters such as !@#$%^&*() and more, as long as they fall between the quotation marks, which indicates that they are part of the string sentence or word.
Check out the full tutorial on Python Strings for more in depth information.
Boolean Data Types
Booleans (bool) represent one of two values: True or False.
In Python programming you often need to know if an expression is True or False. When you compare two values, the expression is evaluated in numerous ways, in order for Python to return the Boolean answer.
Booleans with Comparison Operators
For example, Booleans can be used in conjunction with Comparison Operators (greater than, equal to, less than), to test if two numbers if the statements are true or false.
print(10 > 8)
print(10 == 8)
print(10 < 8)
#>> True
#>> False
#>> False
Booleans with if/else Statements
Booleans are also commonly used inside of if/else Statements, outputting different results, depending on the Comparison Operator (<) in this case.
x = 234
y = 38
if b > a:
print("y is greater than x")
else:
print("y is not greater than x")
#>> b is not greater than a
Sequence Data Types
The three main Sequence Data Types in Python are Lists (list), Tuples (tup) and Range (range).
Lists (list) in Python
Lists are used to store multiple values into a single variable.
Python Lists are created using square brackets [ ].
A List is assigned to a Variable name as follows:
List_Variable_Name = [List_Element0, List_Element1, List_Element2, List_Element3]
Here is an example of a List of three fruit Elements, assigned to a Variable named “fruit_list”:
fruit_list = ["apple", "orange", "banana"]
print(fruit_list)
#>> ['apple', 'orange', 'banana']
A single Python List can contain many different Data Type Elements, including Integers, Strings, Float and Boolean values:
mixed_List = [14, ”welcome”, 365.34, True]
print(mixed_List)
#>> [14, ”welcome”, 365.34, True]
Lists are Ordered, Mutable and Allow for Duplicates
The Elements in a List are Ordered, Mutable, and allow for Duplicate Elements.
The Elements of a Python List have a defined order, and that order will not change. If you were to add new Elements to a List, those new Elements will be placed at the end of the List.
Python Lists are also Mutable, meaning that we can change, add and remove Elements in a List, after it has been created.
Python Lists also allow for Duplicate Elements:
fruit_list = ["apple", "orange", "banana", "apple"]
print(fruit_list)
#>> ['apple', 'orange', 'banana', "apple]
Here we can see that we have two copies of “apple”, which shows that Python Lists allow for duplicate elements.
Check out the full tutorial on Python Lists for more in depth information.
Tuples (tuple) in Python
Python Tuples are similar to Lists, except that a Tuple cannot be changed after its creation.
Tuples are created using parentheses ( ).
A Tuple is assigned to a Variable name as follows:
Tuple_Variable_Name = (Tuple_Element0, Tuple_Element1, Tuple_Element2, Tuple_Element3)
Here is an example of a Tuple of three fruit Elements, assigned to a Variable named “fruit_list”:
fruit_tuple = ("apple", "orange", "banana")
print(fruit_tuple)
#>> ("apple", "orange", "banana")
A single Python Tuple can contain many different Data Type Elements, including Integers, Strings, Float and Boolean values:
mixed_Tuple = (14, ”welcome”, 365.34, True)
print(mixed_Tuple)
#>> (14, ”welcome”, 365.34, True)
Tuples are Ordered, Immutable and Allow for Duplicates
The Elements in a Set are Ordered, Immutable and allow for Duplicate Elements.
The Elements of a Python Tuple have a defined order, and that order will not change. If you were to add new Elements to a Tuple, those new Elements will be placed at the end of the Tuple.
Elements in a Tuple are also Immutable, meaning that we cannot change the Elements after the Tuple has been created.
Tuples also allow for Duplicate Elements :
fruit_tuple = ("apple", "orange", "banana", "apple")
print(fruit_tuple)
#>> ("apple", "orange", "banana", "apple")
Here we can see that we have two copies of “apple”, which shows that Python Tuples allow for Duplicate Elements.
Check out the full tutorial on Python Tuples for more in depth information.
Range (range) in Python
x = range(6)
for n in x:
print(n)
X>> 0
X>> 1
X>> 2
X>> 3
X>> 4
X>> 5
Syntax
Range can be customized to suit your needs using the start, stop and step syntax parameter values:
range(start, stop, step)
Parameter Values
- Start : Optional. An integer number specifying at which position to start. Default is 0
- Stop : Required. An integer number specifying at which position the range should stop, but is not included.
- Step : Optional. An integer number specifying the increment of the next range value. Default is 1
Start Parameter Value
In the example above, we only made use of the Stop Parameter value which was 6. Let’s now use the Start value of 3, to customize the range we want:
x = range(3, 6)
for n in x:
print(n)
X>> 3
X>> 4
X>> 5
This time the range started at 3 instead of the default 0, as we specified it in the range function.
Step Parameter Value
Now, let’s add in a Step value of 2, into the function as well:
x = range(3, 21, 2)
for n in x:
print(n)
X>> 3
X>> 5
X>> 7
X>> 9
X>> 11
X>> 13
X>> 15
X>> 17
X>> 19
As you can see, we Started the range at 3 once again, but this time told it to go all the way to 21, using a Step value of 2.
Note that as mentioned earlier, 21 was not included in the range, even though the last output integer of 19 + a step of would equal 21. The Stop parameter value is never included in the range.
Mapping Data Types
There is currently only one Mapping Data Type, known as Dictionaries (dict).
Dictionaries (dict)
Python Dictionaries are used to store data values in the KEY:VALUE pair format.
Just like Sets (set), Dictionaries (dict) also make use of curly brackets { }.
Dictionary_Variable_Name = {Key0: Value0, Key1: Value1, Key2: Value2, Key3: Value3}
A Dictionary Data type is therefore created as {key:value}, such as {“brand”: “model”}.
car_dictionary = {"BMW": "M5", "Porsche": "Carrera", "Mercedes": "AMG GT"}
print(car_dictionary)
#>> {'BMW': 'M5', 'Porsche': 'Carrera', 'Mercedes': 'AMG GT'}
Dictionaries can also be used to store different specs of a car, such as the brand, model and manufacturing year as follows:
car_dict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(car_dict)
#>> {'brand': 'Ford', 'model': 'Mustang', 'year': 1964}
Here a comma “,” was used at the end of each KEY:VALUE pair in order to break them up into separate lines, so that it’s easier to read. The output result is however the same.
A single Python Dictionary can contain many different Data Type Elements, including Integers, Strings, Float and Boolean values:
mixed_Dictionary = {"The sky is blue": 1.3, 5: 25, True: "Hello"} #int, float, string, bool
print(mixed_Dictionary)
#>> {'The sky is blue': 1.3, 5: 25, True: 'Hello'}
Dictionary Items are Ordered, Mutable and Don’t allow for Duplicates
A Dictionary is a collection which is Ordered, Mutable and Don’t allow for Duplicate KEY:VALUE pairs.
The KEY:VALUE pairs of a Python List have a defined order, and that order will not change. If you were to add new KEY:VALUE pairs to a Dictionary, then they will be placed at the end of the Dictionary.
Python Dictionaries are also Mutable, meaning that we can change, add and remove KEY:VALUE pairs in a Dictionary, after it has been created.
Dictionaries do not allow for duplicate KEY:VALUE pairs, so you cannot have two of the same:
car_dict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
"year": 1975
}
print(car_dict)
#>> {'brand': 'Ford', 'model': 'Mustang', 'year': 1975}
Note that the second or last year was output, so if there is a duplication, all the ones above the last entry will be ignored.
Check out the full tutorial on Python Dictionaries for more in depth information.
Set Data Types
There are two kinds of sets in Python, Sets (set) and Frozen Sets (frozenset)
Sets (set) in Python
Sets are used to store multiple values in a single variable.Python Sets are created using curly brackets { }, although it’s not the data type that uses them, as Dictionaries (dict) also do.
A Set is assigned to a Variable name as follows:
Set_Variable_Name = {Set_Element0, Set_Element1, Set_Element2, Set_Element3}
Here is an example of a Set of three fruit Elements, assigned to a Variable named “fruit_set”:
fruit_set = {"apple", "orange", "banana"}
print(fruit_set)
#>> {"orange", "apple", "banana"}
A single Python Set can contain many different Data Type Elements, including Integers, Strings, Float and Boolean values:
mixed_Set = {14, ”welcome”, 365.34, True}
print(mixed_Set)
#>> {14, ”welcome”, 365.34, True}
Sets are Unordered & Immutable and Don’t allow for Duplicates
The Elements in a Set are Unordered, Immutable, and do not allow for Duplicate Elements.
The Elements of a Python Tuple have no defined order, meaning that the output of a Set is randomized, everytime you run a Set. For this reason, a Python Set cannot be referred to by index or key.
Elements in a set are also Immutable, meaning that we cannot change the Elements after the Set has been created. You can however add and remove Elements.
Sets DO NOT allow for Duplicate Elements, and therefore you cannot have two Elements with the same name.
fruit_set = {"apple", "orange", "banana", "apple"}
print(fruit_set)
#>> {"banana", "apple", "orange"}
Check out the full tutorial on Python Sets for more in depth information.
Frozen Sets (frozenset) in Python
Frozen set is simply an Immutable version of a Python Set, which is normally Mutable.
Therefore, Elements of a Set can be modified at any time, while Elements of the Frozen Set remain the same after creation.
The frozenset() Method is used to return an Immutable frozenset object, which turns a Mutable object into an Immutable object.
For example, we already know that a List (list) is a Mutable Data Type, therefore we can use a Frozen Set (frozenset) to make it Immutable.
fruit_list = ["apple", "orange", "banana"]
fruit_list.append('kiwi') # Adding “kiwi” into the list item values
print(fruit_list)
#>> ['apple', 'banana', 'orange', 'kiwi']
However if we now use the frozenset() Method, it makes it Immutable, in which case we cannot use the .append() Method to add the “grape” Element to it.
fruit_list = ["apple", "orange", "banana"]
x = frozen_set(fruit_list)
x.append(“grape”)
print(x)
#>> AttributeError: 'frozenset' object has no attribute 'append'
How to Check for a Data Type in Python
With a lot of Data Types available to use in Python, it can be very useful to be able to check what Data Type a specific Variable is.To Check a Data Type in Python we use the “type()” function.