
Python Data Types define the characteristics or the nature of the data that variables hold. This facilitates the programmers’ ability to work with data and perform operations effectively and efficiently. Data Types dictate the way data is stored in the computer’s memory.
Similar to any other programming language Python has a list of Data Types as shown in the following Table:
Text | str | ||
Numeric | int | float | complex |
Sequence | list | tuple | range |
Mapping | dict | ||
Set | set | frozenset | |
Boolean | bool | ||
Binary | bytearray | memoryview | |
NoneType | None |
Table of Contents
String Data Type in Python
The string data type in Python is used to represent a sequence of characters. This is mainly used for storing either a single or multiple set of characters. The syntax of Strings is simple, just put the character(s) within either single quote ('...'
) or double quotes (“…”). Inside these quotes, you can store Numbers, Letters, Spaces, or even special characters.
Note: Python Strings use the Unicode standard to represent characters. This makes the Python language interesting or even popular as it can represent characters from any language or script and this makes it easier for people working with multilingual text data
The following example shows how to create a string variable and assign values:
# EXAMPLE 1: Create a Python Variable and store it a String value
# Using single quate
var_str1 = 'This is a String'
# Using double quate
var_str2 = "This is a String"
print(var_str1)
print(var_str2)
# String can contain Numbers, Letters, Spaces, or even special characters
var_str3 = "This is a String 101, #tag ß"
print(var_str3)
The output of the above code reads as follows:
This is a String
This is a String
This is a String 101, #tag ß
Create String Variable and Assign Multiline String Value in Python
In Python, you can assign a variable a multiline text or string which contains several lines of text paragraphs. To enable this, you can use three quotes (either triple single quotes or triple double quotes).
The following example shows how to create a string variable and assign multiline values:
# EXAMPLE 2: Create a Python Variable and store it a Multiline value
# Using Multiline String using triple single quotes
var_mult_li_str1 = '''Lorem Ipsum is simply dummy text of the printing and typesetting industry.
Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an
unknown printer took a galley of type and scrambled it to make a type specimen book.
'''
# Using Multiline String using triple double quotes
var_mult_li_str2 = """It is a long established fact that a reader will be distracted by the readable
content of a page when looking at its layout. The point of using Lorem Ipsum is that it has
a more-or-less normal distribution of letters, as opposed to using 'Content here, content here',
making it look like readable English."""
print(var_mult_li_str1)
print(var_mult_li_str2)
The output of the above code reads as follows:
Lorem Ipsum is simply dummy text of the printing and typesetting industry.
Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an
unknown printer took a galley of type and scrambled it to make a type specimen book.
It is a long established fact that a reader will be distracted by the readable
content of a page when looking at its layout. The point of using Lorem Ipsum is that it has
a more-or-less normal distribution of letters, as opposed to using 'Content here, content here',
making it look like readable English.
Note: Python uses the three quotes (either triple single quotes or triple double quotes) as multiline comments, therefore it treats the string as a normal string literal since it does not assign into a variable.
Concatenate Two Text Strings in Python
In Python, you can able to join or combine two strings that contain separate string variables. To do that we use +
sign operator to concatenate two string values.
The following example shows how to concatenate two strings using the +
operator:
# EXAMPLE 3: Concatenate two text strings in Python
# Concatenate two text strings in Python without using a variable
print("Abraham" + " " + "Moses")
# Concatenate two text strings in Python using a variable
first_name = "Abraham "
second_name = "Moses"
full_name = first_name + second_name
print(full_name)
# Or you can Concatenate them inside the print() function
print(first_name + second_name)
The output of the above code reads as follows:
Abraham Moses
Abraham Moses
Abraham Moses
Learn more about string arrays, string slicing, string formatting, and string methods.
Integer Data Type in Python
Python integer data types are used to represent whole numbers including positive, negative, or zero, and ignore fractions or decimal points. In Python, you can store integers in unlimited sizes as long as you have enough memory storage.
In the following example we create an integer variable and assign whole numbers:
# Create integer variable and assign values
var_weight = 118
var_height = 2
# Display the weight and height
print(var_weight)
print(var_height)
The output of the above code reads as follows:
118
2
Assigning Zero, Negative, and Decimal Values to Integers in Python
Although integer data types in Python do not support decimals, there are cases where you need to assign zero, negative, or decimal values to an integer variable. However, the integer variable will ignore the decimal values and to do so you need to use the int()
method otherwise the data type of that variable will become float. This means using the int()
method will convert the values into integers and it will lead to losing all the decimal points. You should aware of this when you are dealing with real data.
In the following example, we show how to assign zero, negative, or decimal values to an integer variable in Python:
# Assign Zero, Negative and Decimal values
var_x = 0
var_y = -93
var_z = int(9.34)
print(var_x)
print(var_y)
print(var_z)
The output of the above code reads as follows:
0
-93
9
Perform Mathematical Operations on Integer Values in Python
When using integers or whole number values you can perform several mathematical or arithmetic operations, including addition, subtraction, multiplication, division, or exponentiation.
In the following example, we show how to perform some arithmetic operations on integer values in Python:
# perform some mathematical/arithmetic operations on integer values in Python
var_weight = 116
var_height = 2
# Perform BMI calculation
var_height_sq = var_height*var_height
var_bmi = int(var_weight/var_height_sq)
# Display the weight, height and BMI
print(var_weight)
print(var_height)
print(var_bmi)
"""Formula of BMI is weight in kilograms divided by height in meters squared"""
The output of the above code reads as follows:
116
2
29
Note: In real-world mathematical operations, it is highly possible to get decimal values, especially when using division (/
) operators. However, converting your results into integers will result in losing all the decimal points.
The Difference Between int and long: Integer Types in Python
Previous Python versions have two types of integers such as int
and long
. The int
data type is the standard one and it is used to represent whole numbers as we explained earlier. While the long data type was used to represent long integers that range from -2147483648 to 2147483647. However, in Python version 3, these differences were neglected and long
type is no longer needed, since the int
can handle both short and large integer values. Learn int data type and perform more arithmetic operations further.
Float Data Type in Python
Python float data type is used to represent floating-point numbers or numbers with a decimal point.
In the following example we create a float variable and assign numbers with a decimal point:
# Create float variable and assign values
var_weight = 118.89
var_height = 1.89
# Display the weight and height
print(var_weight)
print(var_height)
The output of the above code reads as follows:
118.89
1.89
Perform Mathematical Operations on Float Values in Python
When using float or numeric values with decimal points you can perform several arithmetic or mathematical operations, including addition, subtraction, multiplication, division, or exponentiation.
In the following example, we show how to perform some mathematical operations on float values in Python:
# perform some mathematical/arithmetic operations on float values in Python
var_weight = 118.89
var_height = 1.89
# Perform BMI calculation
var_height_sq = var_height*var_height
var_bmi = var_weight/var_height_sq
# Display the weight, height and BMI
print(var_weight)
print(var_height)
print(var_bmi)
The output of the above code reads as follows:
118.89
1.89
33.28294280675233
Note: In Python, you can trim or round the long decimal points because sometimes you might encounter unexpected behavior when performing arithmetic operations with very large or very small float numbers. Therefore you can use the round()
function to specify the number of decimals you want to display or you can use thedecimal
module to perform more operations.
Round Floating-Point Numbers with Python’s round() Function
In Python, to round floating-point numbers we useround()
function. When using the round()
function, the users can specify two arguments: first is the number to be rounded and the second is the number of decimals to use when rounding the decimal numbers.
Note: The second argument is optional and by default the function round to its nearest integer.
In the following example, we show how to round floating-point numbers in Python:
# Round Floating-Point Numbers with Python's round() Function:
# round() function without variable
print(round(26.567456, 4))
var_x = 76.897558
# round() function without second argument
print(round(var_x))
# round it with 3 decimal points
print(round(var_x, 3))
# Perform some operations in the first argument and round it with 2 point
var_x = round(var_x*3, 2)
print(var_x)
The output of the above code reads as follows:
26.5675
77
76.898
230.69
Use Negative Values for the Second Argument of the round() Function to Round the Number
In Python, you can also use negative values for the second argument to round the number to the nearest 10, 100, 1000, etc.
This means if you pass -1
in the second argument, the number will be rounded to the nearest 10, and if you provide -2
, the number will be rounded to the nearest 100, and the rest goes.
In the following example, we show how to round numbers to the nearest digits, in Python:
# use negative values for the second argument to round the number
print(round(264.367456, -1))
var_x = 765678.897558
# round() function without second argument
print(round(var_x, -2))
# round the integer value
print(round(58212, -1))
The output of the above code reads as follows:
260.0
765700.0
58210
Complex Data Type in Python
The complex data type is used to represent what is called complex numbers. These numbers can contain both real and imaginary parts. The imaginary part uses a J
or j
character to write it.
For example, the complex number 7 + 4j. The number 7 represents the real part while the 4 represents the imaginary part.
In the following example, we show how to create a variable with complex type, in Python:
# create complex variable in Python
var_complex = 7+4j
print(var_complex)
var_complex = 3J
print(var_complex)
# check its type
print(type(var_complex))
The output of the above code reads as follows:
(7+4j)
3j
<class 'complex'>
Note: The last line of the above code checks the type of the variable using type()
the function. This function is used to check the data type of variable or value.
Perform Mathematical Operations on Complex Values in Python
Complex data types are commonly used in the field of engineering such as Physics, electrical engineering, and computer science because they might solve mathematical problems.
When assigning value to the complex variable, you can separate the real and imaginary value using the plus +
sign, but if you use the multiplication *
and /
sign it will perform operations accordingly.
Note: You can use space between the real and the imaginary parts but the compiler will ignore it as shown in the following examples.
In the following example, we show how to assign different complex values in variables using different signs in between the real and imaginary parts, in Python:
# create complex variable assign diffrent values in Python
var_complex1 = 7 + 4j
var_complex3 = 7 * 4j
var_complex4 = 7 / 4j
print(var_complex1)
print(var_complex2)
print(var_complex3)
print(var_complex4)
The output of the above code reads as follows:
(7+4j)
28j
-1.75j
Note: Avoid using commas ,
sign in between the real and the imaginary part otherwise, it will become a tuple. Example: var_complex2 = 2, 3j
In the following example, we Perform Mathematical Operations on Complex Values in Python:
# Perform Mathematical Operations on Complex Values in Python
a = 7+4j
b = 2 - 3j
c = 5 * 6j
d = 8 / 1j
print(a)
print(b)
print(c)
print(d)
print()
print(a + b)
print(b - a)
print(c * d)
print(d/c)
The output of the above code reads as follows:
(7+4j)
(2-3j)
30j
-8j
(9+1j)
(-5-7j)
(240+0j)
(-0.26666666666666666-0j)
The mathematical operations performed above are simple, and they will be performed like this: a variable contains 7 real numbers and 4 imaginary numbers (4 is positive) while the b variable has 2 real numbers and -3 imaginary numbers (the -3 has a negative prefix). Therefore the a+b
is equal to (7+2) = 9 and (4+-3) or (4-3) = 1 (the minus will have the upper hand). The final result is 9+1j. Because the operation of each part will be conducted separately and concatenated finally. The rest of the arithmetic operations will be done like this. Learn complex data type and perform more arithmetic operations further.
Bool Data Type in Python
Bool or Booleans is another data type that is used to represent the logical values of True
or False
or One or Two. This is mainly used when we are dealing with conditional expressions to take certain decisions during the program execution. True and False are predefined values and they can indicate if certain expressions are True or False.
In the following example, we show how to work with boolean type variables in Python:
# Bool Data Type in Python
a = 10 > 2
b = 30 < 20
print(a) # a contains True = 1
print(b) # b contains False = 0
print(a > b) # 1 > 0 = True
The output of the above code reads as follows:
True
False
True
Note: The computer represents the True
into 1
and the False
translates to 0
. So if we say True > False = (1 > 0)
and the result is True
. The last line in the above code reads a > b
will be translated like that.
Evaluation of Variables in Python using bool() Function
In Python, we can evaluate values and variables using the built-in bool()
function. The bool()
function returns a Boolean value of True
or False
based on the input value.
In the following example, we show how to work with the bool() function in Python:
# Bool() Function in Python
a = bool(10 > 2)
b = bool("Python")
c = bool(28)
print(a)
print(b)
print(c)
print(bool(0))
print(bool(""))
The output of the above code reads as follows:
True
True
True
False
False
Note: If a variable has empty values it will be evaluated as False such as ""
, 0
, or empty tuples ()
, empty lists []
, empty sets {}
, we will learn all these in the following topics.
Bytes Data Type in Python
In Python, the Bytes data type is a fixed size of a sequence of bytes that can be stored in the memory. This kind of data type is used in the files such as images, audio, or videos as these types of files can contain binary data types.
In Python, we can create a bytes variable by prefixing the “value” with a b
character. This syntax tells Python compilers to create a bytes object.
Note: The bytes object contains the ASCII codes for the characters you provided.
In the following example, we create a variable with byte type in Python:
# Bytes Data Type in Python
var_bytes = b"Python Bytes"
print(var_bytes)
# Check its type
print(type(var_bytes))
The output of the above code reads as follows:
b'Python Bytes'
<class 'bytes'="">
Alternative Way to Create bytes in Python
Here I show you how you can also create a bytes variable using a built-in function or constructor called bytes()
. Inside the bytes()
function you can pass integers, lists, sets, or even strings.
Note: When you are using the bytes() function while passing strings you must prefix the b
character otherwise it will trigger an error.
In the following example, we create a variable using the bytes() function in Python:
# Alternative ways to define byte variable in Python using bytes() function
var_byte1 = bytes(12) # passing a integer
var_byte2 = bytes([12, 1, 3]) # passing a list of integers
var_byte3 = bytes(b"Hello Python") # passing a String
print(type(var_byte1))
print(type(var_byte2))
print(type(var_byte3))
The output of the above code reads as follows:
<class 'bytes'>
<class 'bytes'>
<class 'bytes'>
Note: The return values of thebytes()
function cannot be modified.
In the following example, we try to modify the bytes data in Python:
# Modify the bytes() data
var_byte1 = bytes([12, 1, 3]) # passing a list of integers
var_byte2 = bytes(b"Hello Python") # passing a String
print(var_byte2[0])
print(var_byte2[2:4])
var_byte1[0] = 2
The output of the above code reads as follows:
72
b'll'
Traceback (most recent call last):
File "c:\Bytes_variable.py", line 224, in <module>
var_byte1[0] = 2
~~~~~~~~~^^^
TypeError: 'bytes' object does not support item assignment
The above code was successful except for the final line which tries to modify the value of the bytes variable using their index. The error type is self-explanatory as it says “TypeError: ‘bytes’ object does not support item assignment“.
Bytearray Data Type in Python
In Python, bytearray represents a sequence of integers that ranges from 0 to 255. The value in a bytearray object can be modified after it has been created. To create bytearray we use a built-in function/constructor called bytearray()
It is worth mentioning that the main difference between bytes()
and bytearray()
functions are the mutability feature. As we said earlier the bytes()
values are not mutable and they will only return an immutable object which cannot be modified, while the bytearray()
values are mutable and they can return a mutable object which can be modified after it has been created.
In the following example, we create a variable using bytearray() function in Python:
# Bytearray Data Type in Python
var_bytearray1 = bytearray(b"Hello Python")
var_bytearray2 = bytearray(85)
var_bytearray3 = bytearray([12, 1, 3, 6, 7])
# display them on the console
print(var_bytearray1)
print(var_bytearray2)
print(var_bytearray3)
# display their data type using type() function
print(type(var_bytearray1))
print(type(var_bytearray2))
print(type(var_bytearray3))
The output of the above code reads as follows:
bytearray(b'Hello Python')
bytearray(b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')
bytearray(b'\x0c\x01\x03\x06\x07')
<class 'bytearray'>
<class 'bytearray'>
<class 'bytearray'>
The bytearray is useful in applications that are processing image files especially when they are manipulating its features or contents such as colors, shades, etc. Other applications used bytearray include cryptography systems to secure communications between the networks.
Manipulate Internal Data with bytearray in Python
As we mentioned earlier, the bytearray()
values are mutable which means we can modify them whenever it is necessary after it has been created.
In the following example, we modify the data in a bytearray() variable in Python:
# Modify the Bytearray() data in Python
var_bytearray1 = bytearray(b"Hello Python")
var_bytearray2 = bytearray(85)
var_bytearray3 = bytearray([12, 1, 3, 6, 7])
# display them on the console
var_bytearray1[0] = 12
print(var_bytearray1[0])
var_bytearray2[3] = 34
print(var_bytearray2[3])
var_bytearray3[len(var_bytearray3)-1] = 2
print(var_bytearray3[len(var_bytearray3)-1])
print()
print(len(var_bytearray3))
# ==========================
The output of the above code reads as follows:
12
34
2
5
Note: we use the len()
function to access the size or the total number of items a variable has, such as Sets. Therefore the len(variable) starts counting from 1 to n (n is the position of the last element), therefore when we modify a specific item use its index, thus, the index counting will start from 0 up to n. In this case, the var_bytearray3
has a length of 5, but if we need to modify the last item we use 5-1 which is the 4th one. More examples about the len()
function we will learn in our Python Biult-in functions.
Memoryview Data Type in Python
In Pythons, the memoryview data type allows us to access the internal buffer of a bytes-like object, such as a bytearray or a bytes object, because these data types or objects have a fixed-sizes and contiguous memory layout, which makes it easier or possible to directly access their memory.
To create memoryview type variable we use a built-in function or constructor called memoryview()
. This returns a memory view object from the object you pass it.
In the following example, we create a variable using memoryview() function in Python:
# Memoryview Data Type in Python
var_memoryview = memoryview(b"Hello Python")
print(var_memoryview[0])
print(var_memoryview[1])
print(var_memoryview[3])
print(type(var_memoryview))
The output of the above code reads as follows:
72
101
108
<class 'memoryview'>
Note: Avoid passing the memoryview()
function is not a bytes-like object such as byte or bytearray and you cannot pass object like ‘int‘ or ‘list‘ or ‘sets‘ etc, otherwise, it will trigger an error saying “TypeError: memoryview: a bytes-like object is required, not ‘int‘”
The following example shows what not to do when using the memoryview()
in Python:
# What not to do when using the memoryview()in Python:
# in Memoryview you cannot pass 'int' and it only requires a bytes-like object
var_memoryview1 = memoryview(123)
# in Memoryview you cannot pass 'list' or 'set' ect and it only requires a bytes-like object
var_memoryview2 = memoryview([65, 8, 95, 2, 4])
The output of the above code reads as follows:
<class 'memoryview'>
Traceback (most recent call last):
File "c:\memoryview_variable.py", line 254, in <module>
var_memoryview1 = memoryview(123)
^^^^^^^^^^^^^^^
TypeError: memoryview: a bytes-like object is required, not 'int'
Instead, you can do as follows by passing them byte objects:
# Passing byte objects to the memoryview() function
var_byte1 = bytes(12) # passing a integer
var_byte2 = bytearray([12, 4, 3]) # passing a list of integers
var_byte3 = bytes(b"Hello Python") # passing a String
var_memoryview1 = memoryview(var_byte1)
var_memoryview2 = memoryview(var_byte2)
var_memoryview3 = memoryview(var_byte3)
print(var_memoryview1[0])
print(var_memoryview2[1])
print(var_memoryview3[3])
The output of the above code reads as follows:
0
4
108
Manipulate Internal Data with memoryview in Python
The following Python code shows how you can manipulate the data while they are in the buffer or the memory through the memoryview.
# Manipulating Internal Data with memoryview in Python
var_byte1 = bytearray(b'Python Code')
var_byte2 = bytearray(b"Hello Python")
var_memoryview1 = memoryview(var_byte1)
var_memoryview2 = memoryview(var_byte2)
# Before manipulating
print("Before manipulating")
print(var_byte1)
print(var_byte2)
var_memoryview1[1] = 100
var_memoryview2[len(var_byte2)-1] = 90
print()
# After manipulating
print("After manipulating")
print(var_byte1)
print(var_byte2)
The output of the above code reads as follows:
Before manipulating
bytearray(b'Python Code')
bytearray(b'Hello Python')
After manipulating
bytearray(b'Pdthon Code')
bytearray(b'Hello PythoZ')
In the above code, we have modified the value of the second value of the var_byte1
variable ‘y‘ through the var_memoryview1
which is a memory view object and replaced it with a lowercase ‘d‘ (its ASCII = 100). Meanwhile, the last value of ‘n‘ of the var_byte2
variable was also modified through a memory view object named var_memoryview2
and replaced the upper case of ‘Z‘ (its ASCII = 90).
Set Data Type in Python
In Python, a Set is a type of variable that can hold multiple items. This means Sets can store a collection of unique elements. Set variables have the following characteristics;
- Python set data type can store multiple items but each has to be unique: This means it can only accept each item or value to be unique it will not accept duplicates. For example, if you store the ‘Python‘ word three times, it will only return one item out of the three.
- Python set data type can store multiple items with different data types: This means, one or multiple items in the set can represent different data types that Python supports such as integer, string, float, etc.
- Items of Python set data type are not ordered (unordered): This means the items will be displayed in an unordered way or in random order and this is what makes them unpredictable as they are displayed in ways they are not presented during the declaration.
- Stored items in Python set data type are unchangeable: This means the items in the set cannot be changed after it has been created, but you can only remove items and add new items.
In Python we can create a set, using curly braces {}
or using a built-in function/constructor called set()
.
In the following example, we create a set variable and give multiple different items in Python:
# Create a set variable and give multiple different items in Python
var_set = {"Hello", "Python", "-V", 3, True}
# Display the set items on the console
print(var_set)
The output of the above code reads as follows:
{True, 3, 'Hello', '-V', 'Python'}
As shown in the above code, we have created a variable called var_set
and when we are assigning set items we have used curly braces {}
. The output of the above code also shows that the values were not displayed in the ways they are presented.
Python Sets: Items have to be Unique
It is true that, in Python, the items in a set have to be unique. This means that you cannot keep duplicates in a set. Although it will not trigger an error, the Python compiler will ignore the duplicate items and only consider one of these items.
In the following example, we show you this in practice:
# Create a set variable and give duplicate items in Python
var_set = {"Hello", "Python", "-V", "Python", 3, "Python", True, "-V"}
# Display the set items on the console
print(var_set)
The output of the above code reads as follows:
{True, 'Hello', 3, 'Python', '-V'}
In the above code the word ”Python” was mentioned three items and the word “-V” was mentioned twice. Therefore, we run, and the compiler ignores the duplicates and only keeps one of these values in the set.
Python Sets: Store Multiple Data Types
In Python, the data in the set variables can represent any data type that Python supports such as integer, string, float, bool, and many more.
In the following example, we show you this in practice:
# Create a set variable and give items with diffrent data types in Python
var_set = {"Hello", 3, True, 2.89, b"Z"}
# Display the set items on the console
print(var_set)
The output of the above code reads as follows:
{'Hello', True, 2.89, 3, b'Z'}
Python Sets: Items are Unordered
It is true that Python sets are unordered which means that the orders in the data are not defined that’s why they appear in different orders every time we run the code. The root cause of this is the lack of index keys. This leads that the data being stored or retrieved in an unpredictable way.
In the following example, we show you this in practice:
# Create a set variable and give items with diffrent data types in Python
var_set1 = {"Hello", 3, 89, 2.89, b"Z", (2, 5, 7)}
var_set2 = {7, 3, 8.9, 2.89, b"yu7", (0, 28, "set")}
# Display the set items on the console and obser their display order
print(var_set1)
print(var_set2)
The output of the above code reads as follows:
{(2, 5, 7), 2.89, 3, b'Z', 'Hello', 89}
{2.89, 3, (0, 28, 'set'), 7, 8.9, b'yu7'}
The above code was not displayed in the orders they are presented during its declaration.
Python Sets: Items are Unchangeable
In Python, sets are immutable objects, which means you can’t change the individual items in the set after it has been created, but you can only remove items and add new items.
In the following example, we show you this in practice:
# Create a set variable and give items with diffrent data types in Python
var_set = {"Hello", 3, 89, 2.89, b"Z", (2, 5, 7)}
# Try to change items using index key
var_set[3] = 9
# Display the set items on the console
print(var_set)
The output of the above code reads as follows:
Traceback (most recent call last):
File "c:\Users\sets_variable.py", line 356, in <module>
var_set[3] = 9
~~~~~~~^^^
TypeError: 'set' object does not support item assignment
In the above code, we tried to change one of the existing items in the set using the index key, in this case, sets do not support this feature and trigger an error saying “TypeError: ‘set’ object does not support item assignment“
Instead, you can remove or add new items as shown in the following example:
# Create a set variable and give items with diffrent data types in Python
var_set = {"Hello", 3, 89, 2.89, b"Z", (2, 5, 7)}
# Remove items from a set using remove() method
var_set.remove(89)
# Display the set items on the console after items is removed
print(var_set)
# add new items from a set using add() method
var_set.add(100)
# Display the set items on the console after items is added
print(var_set)
The output of the above code reads as follows:
{(2, 5, 7), 2.89, 3, 'Hello', b'Z'}
{(2, 5, 7), 2.89, 3, 'Hello', 100, b'Z'}
To remove or add an item in a set we use two methods called remove()
and add()
respectively. These methods take the actual value. More practice related to these methods will be discussed in our Python built-in practices.
Alternative Way to Create Sets in Python
The alternative way of creating Python sets is by using the set()
constructor. This function takes an argument, including other iterable objects or sequences such as lists, tuples, or even another set!
The following example shows how to use the set()
constructor.
# Create a set variable using the set() constructor/function in Python
# the argument is a set
var_set1 = set({"Hello", 3, 89, 2.89, b"Z", (2, 5, 7)})
# Display the set items on the console after items is removed
print(var_set1)
print(type(var_set1))
# the argument is a tuple
var_set2 = set(("Hello", 3, 89, 2.89, b"Z", (2, 5, 7)))
# Display the set items on the console after items is removed
print(var_set2)
print(type(var_set2))
# the argument is a list
var_set3 = set(["Hello", 3, 89, 2.89, b"Z", (2, 5, 7)])
# Display the set items on the console after items is removed
print(var_set3)
print(type(var_set3))
The output of the above code reads as follows:
{(2, 5, 7), 2.89, 3, 'Hello', b'Z', 89}
<class 'set'>
{2.89, 3, 'Hello', b'Z', (2, 5, 7), 89}
<class 'set'>
{2.89, 3, 'Hello', b'Z', (2, 5, 7), 89}
<class 'set'>
Note: In the above code we used Curly braces {}
, parentheses ()
or square brackets []
to enclose the items. All these options create a new set object that contains the items from a set, list, or tuple. This means the set()
constructor converts any data type (such as list, tuple, etc) passed as an argument will be converted into a set.
Frozen Data Type in Python
As we discussed above, the sets are sequential data that are unique, unordered, and unchangeable except when removing and adding new items. Therefore, the Frozen set data type is used to freeze the items and make them unchangeable and unordered after they have been created.
To freeze a set or list or any sequences we use the frozenset()
function.
In the following example, we create a Frozen set variable and give multiple different items in Python:
# Python frozenset Type
# Create a Python frozenset variable and freez lists, sets and tuples
var_set = {"Hello", "V", "Python", "Python", 4, 3, 4j, True}
var_tuple = ("Hello", "V", "Python", "Python", 4, 3, 4j, True)
var_list = ["Hello", "Python", 5.5, 3, 4j, True]
var_frozen_set = frozenset(var_set) # Freeze the set
var_frozen_tuple = frozenset(var_tuple) # Freeze the tuple
var_frozen_list = frozenset(var_list) # Freeze the list
# Display them on the console
print(var_frozen_set)
print(var_frozen_tuple)
print(var_frozen_list)
# Display their type
print(type(var_frozen_set))
print(type(var_frozen_tuple))
print(type(var_frozen_list))
The output of the above code reads as follows:
frozenset({True, 'Python', 3, 4, 'V', 4j, 'Hello'})
frozenset({True, 3, 4, 4j, 'Hello', 'Python', 'V'})
frozenset({True, 3, 5.5, 4j, 'Hello', 'Python'})
<class 'frozenset'>
<class 'frozenset'>
<class 'frozenset'>
Python Frozen: Items are Unchangeable
In Python, frozenset are immutable objects, which means you can’t change the individual items in the frozenset after it has been created, this means you cannot even remove or add new items.
In the following example, we show you this in practice:
# Modify, change frozenset
# Create a Python frozenset variable and freez lists
var_list = ["Hello", "Python", 5.5, 3, 4j, True]
var_frozen_list = frozenset(var_list) # Freeze the list
# Trying to change item in the frozenset
var_frozen_list[3] = "Java"
The output of the above code reads as follows:
Traceback (most recent call last):
File "c:\Users\frozen_set_variable.py", line 700, in <module>
var_frozen_list[3] = "Java"
~~~~~~~~~~~~~~~^^^
TypeError: 'frozenset' object does not support item assignment
The above code has triggered an error after we tried to make changes to items in the frozenset and the error says “TypeError: ‘frozenset’ object does not support item assignment“.
List Data Type in Python
List data type list variables are used to store multiple items in a variable. This means list variables can store a collection of ordered and changeable items. List variables have the following characteristics;
- Items of Python list data type are changeable: This means the items in the list can be changed, removed, or added new items after it has been created.
- Python list data type allows duplicate items: This means it can accept similar items to appear or to keep them in the list (accept duplicates). For example, you can store the word ‘Python‘ three times, and it will accept it. Because items in the list are indexed.
- Items of Python list data type are ordered: This means the items in the list have a defined order and will be displayed in an ordered way. Meaning that they are displayed in ways they are presented during the declaration. Such an order will not change. In case you add a new item (e.g. using
appen()
method), such an item will be placed at end of the list. - Python list data type can store multiple items with different data types: This means, one or multiple items in the list can represent different data types that Python supports such as integer, string, float, etc.
In Python we can create a list, using square brackets []
or using a built-in function/constructor called list()
.
In the following example, we create a list variable and give multiple different items in Python:
# Create a list variable and give multiple different items in Python
var_list = ["I Love", "Python", 455, 3, True]
# Display the set items on the console
print(var_list)
print(type(var_list))
The output of the above code reads as follows:
['I Love', 'Python', 455, 3, True]
<class 'list'>
Python List: Items are Changeable
In Python, List items can be changed, which means users can able to remove, add, or update/change list items after it has been created.
The following example shows how to remove list items in Python:
# Create a list variable and give multiple different items in Python
var_list = ["I Love", "Python", 455, 3, True, "USD", "BTC"]
# Remove items from a list using remove() method
var_list.remove(3)
# Display the list items on the console after items is removed
print(var_list)
# Remove items from a list using pop() method
var_list.pop(3)
# Display the list items on the console after items is removed
print(var_list)
The output of the above code reads as follows:
['I Love', 'Python', 455, True, 'USD', 'BTC']
['I Love', 'Python', 455, 'USD', 'BTC']
The above code only shows how to remove a list item using two different methods. The first method used is the remove()
method, this method takes an argument which is the item to be removed. The second method is the pop()
method and which takes the index value of the item to be removed. In this case, we pass him index 3 (position) and the value found in that position 3 is a ‘True‘ item, then it will be removed from the list.
The following example shows how to add items to a list in Python:
# Create a list variable and give multiple different items in Python
var_list = ["I Love", "Python", 455, "USD", "BTC"]
# add new items in a list using append() method
var_list.append(100) # adds item at end of the list
var_list.append(False) # adds item at end of the list
# Display the list items on the console after items is added
print(var_list)
# or use insert() method to add list item at a specified location
var_list.insert(0, "First")
# Display the list items on the console after items is added
print(var_list)
The output of the above code reads as follows:
['I Love', 'Python', 455, 'USD', 'BTC', 100, False]
['First', 'I Love', 'Python', 455, 'USD', 'BTC', 100, False]
To add a new item to a list, we have used two different methods as shown in the above code. The first method is append()
, it takes a single argument which is the value to be added to the list. This method inserts the new item at end of the list. The second method we have used in the above code is insert()
method, this method takes two arguments: the first argument is the position (or the index) you want to insert the new item and the second argument is the actual value you want to insert in the list.
Note: the insert()
method will not replace the previous item in the list that occupied the specified index. Instead, it will shift all subsequent items to the right, this means they will be pushing the previous item one index to the right.
The following example shows how to change existing list items in Python:
# Create a list variable and give multiple different items in Python
var_list = ["I Love", "Python", 455, "USD", "BTC"]
print("Before change happen")
print(var_list)
# change previous items in a list using their index
var_list[2] = 20 # changes the item in psition 2 (third) of the list to 20
var_list[len(var_list)-1] = "EUR" # changes the last item of the list
# Display the list items on the console after items is added
print()
print("After change happen")
print(var_list)
The output of the above code reads as follows:
Before change happen
['I Love', 'Python', 455, 'USD', 'BTC']
After change happen
['I Love', 'Python', 20, 'USD', 'EUR']
In the above code, to change an existing list item we do not need to use a built-in method, therefore we use the index value of the item we need to change and then assign a new item. For example, this indicates we will change the value in position three (or index 2) to a 20.
On the other hand, we used the len()
function to return the number of elements (or the length) in a list and convert this to an index range. Because the len()
is 1-based and its count starts from 1 to n. This means increases by 1 for each element. For instance, a list with 6 items has a length of 6.
While the index range starts from 0 (0-based) to n and goes up to one less than the length of the list. This is the reason why we subtract 1 from the length returned to get the last index value. For instance var_list[len(var_list)-1] = "EUR"
, the len(var_list)
return the length of var_list
which is 5, therefore the index value of the last item will be 5-1 which is 4, then in index 4 we will be replaced to "EUR"
value.
Python List: Allow Duplicates
In Python, list variables can store multiple items that are similar. Because lists store items in an index-based manner.
In the following example, we show you this in practice:
# Create a list variable and give duplicate items in Python
var_list = ["I Love", 455, "Python", 455, "USD", "USD"]
# Display the list items on the console
print(var_list)
The output of the above code reads as follows:
['I Love', 455, 'Python', 455, 'USD', 'USD']
Python List: Items are Ordered
In Python, list items are ordered, which means that they are stored in a specific order and such order is preserved every time you are interacting with the list items. The list items will be ordered in the ways they are presented during the declaration unless you modify it by either removing or inserting new items at specific locations.
Such consistency or order is key and it allows us to access such items using their index keys.
In the following example, we show you this in practice:
# Python list items are oredered
# Create a list variable in Python
var_list = [1, 4, 7, 8, 2, 4]
# Display the list items on the console
print(var_list)
# Display them using their index value
print(var_list[2]) # accesses the 3th item
print(var_list[4]) # accesses the 5th item
print(var_list[1:4]) # accesses multiple items using range
print(var_list[len(var_list)-1]) # accesses the last item
The output of the above code reads as follows:
[1, 4, 7, 8, 2, 4]
7
2
[4, 7, 8]
4
Python List: Store Multiple Data Types
Similar to sets, in Python, you can store items of different data types within a list variable. For instance, a list variable can contain items that can represent any data type that Python supports such as integer, string, float, bool, and many more.
In the following example, we show you this in practice:
# Create a list variable and give multiple different items in Python
var_list = ["Hello", "Python", 5.5, 3, 4j, True, (1, 5, 9), {5, "Python", 4}]
# Display the set items on the console
print(var_list)
The output of the above code reads as follows:
['Hello', 'Python', 5.5, 3, 4j, True, (1, 5, 9), {'Python', 4, 5}]
Alternative Way to Create List in Python
The alternative way of creating a Python list is by using the list()
constructor. This function takes an argument, including other objects or sequences such as sets, tuples, and others!
The following example shows how to use the list()
constructor.
# Create a list variable and give multiple different items in Python
var_set = {"Hello", "Python", 5.5, 3, 4j, True, (1, 5, 9)}
var_list1 = list(var_set) # converst the set into a list
var_list2 = list([2, 4, 65, 75.2, "hello"])
var_list3 = list()
var_list3.append(3)
var_list3.append("Python")
var_list3.append((2, 5, 6))
var_list3.append(True)
# Display the set items on the console
print(var_list1)
print(var_list2)
print(var_list3)
print(type(var_list1))
print(type(var_list2))
print(type(var_list3))
The output of the above code reads as follows:
[True, 'Hello', 3, (1, 5, 9), 5.5, 4j, 'Python']
[2, 4, 65, 75.2, 'hello']
[3, 'Python', (2, 5, 6), True]
<class 'list'>
<class 'list'>
<class 'list'>
Tuple Data Type in Python
Tuple data type in Python is used to store multiple items in a single variable. Similar to a list, tuple objects are immutable. Which means their items cannot be modified after it has been created. Tuple variables have the following characteristics;
- Python tuple data type allows duplicate items: This means tuples accept multiple similar items to appear or to be stated in the tuple (accept duplicates). For example, you can mention the word ‘Hello‘ five times, and it will accept it. Because each item can be indexed.
- Items of Python tuple data type are ordered: This means that the items in the tuple have a defined order and will be displayed in an ordered way.
- Stored items in Python tuple data type are unchangeable: This means the items in the tuple cannot be changed, removed, or added new items after it has been created.
To define a variable with a tuple type we use parentheses (round brackets) ()
or tuple constructortuple()
.
In the following example, we create a tuple variable and give multiple different items in Python:
# Create a tuple variable and give multiple different items in Python
var_tuple = ("Hello", "Python", "V", 3, 5.5, 3, 4j, True)
# Display the tuple items on the console
print(var_tuple)
# Display and chek its type on the console
print(type(var_tuple))
The output of the above code reads as follows:
('Hello', 'Python', 'V', 3, 5.5, 3, 4j, True)
<class 'tuple'>
Python Tuple: Allow Duplicates
Similar to the list type, tuple variables can also store multiple items that are similar. Because tuples also store items in an index-based manner.
In the following example, we show you this in practice:
# Create a tuple variable and give multiple different items in Python
# Tuples allow duplicates
var_tuple = ("Hello", "V", "Python", "Python", 4, 3, 4j, True)
# Display the tuple items on the console
print(var_tuple)
The output of the above code reads as follows:
('Hello', 'V', 'Python', 'Python', 4, 3, 4j, True)
Python Tuple: Items are Ordered
In Python, tuple items are ordered, which means that they are stored in a specific order and such order is preserved every time you are dealing with the tuple items. The tuple items will be ordered in the ways they are presented during the declaration unless you modify it by either removing or inserting new items at specific locations.
Such consistency or order is key and it allows us to access such items using their index keys.
In the following example, we show you this in practice:
# Create a tuple variable and give multiple different items in Python
# Tuples are ordered
var_tuple = ("Hello", "V", "Python", "Python", 4, 3, 4j, True)
# Display the tuple items on the console
print(var_tuple)
# Display them using their index value
print(var_tuple[2]) # accesses the 3th item
print(var_tuple[4]) # accesses the 5th item
print(var_tuple[1:4]) # accesses multiple items using range
print(var_tuple[len(var_tuple)-1]) # accesses the last item
The output of the above code reads as follows:
('Hello', 'V', 'Python', 'Python', 4, 3, 4j, True)
Python
4
('V', 'Python', 'Python')
True
Python Tuple: Items are Unchangeable
In Python, tuples are immutable objects, which means you can’t change, remove or add items in the set after it has been created.
In the following example, we show you this in practice:
# Create a tuple variable and give items with diffrent data types in Python
var_tuple = ("Hello", "V", "Python", "Python", 4, 3, 4j, True)
# Try to change items using index key
var_tuple[3] = 9
# Display the tuple items on the console
print(var_tuple)
The output of the above code reads as follows:
Traceback (most recent call last):
File "c:\tuple_variable.py", line 549, in <module>
var_tuple[3] = 9
~~~~~~~~~^^^
TypeError: 'tuple' object does not support item assignment
If you try to change a tuple you will encounter an error saying “TypeError: ‘tuple’ object does not support item assignment“. This indicates that the tuples do not accept to reassign value to that position.
Alternative Way to Create Tuple in Python
The alternative way of creating a Python tuple is by using the tuple()
constructor. This function takes an argument, including other objects or sequences such as sets, list, and others.
The following example shows how to use the tuple()
constructor.
# Create a tuple variable and give multiple different items in Python
var_set = {"Hello", "V", "Python", "Python", 4, 3, 4j, True}
var_tuple1 = tuple(var_set) # converst the set into a tuple
var_tuple2 = tuple([2, 4, 65, 75.2, "hello"]) # converst the list into a tuple
# Display the tuple items on the console
print(var_tuple1)
print(var_tuple2)
print(type(var_tuple1))
print(type(var_tuple2))
The output of the above code reads as follows:
(True, 3, 4, 'Python', 'V', 'Hello', 4j)
(2, 4, 65, 75.2, 'hello')
<class 'tuple'>
<class 'tuple'>
Range Function in Python
in Python, range()
is a built-in function that is used to create a sequence of numbers, or we can say it returns a range of numbers. Although, the range function is not a real data type, yet, we used it to generate a series of numbers (integers).
Range values are memory efficient since they will only be generated when needed, while in other sequences such as set, list, or tuples, all the items were prespecified and occupied in the memory. Range values are commonly used in loops.
The following example shows how to use the range()
function to generate a sequence of numbers in Python.
# Create a sequence of data using range() function in Python
var_range1 = range(10)
var_range2 = range(5, 15)
var_range3 = range(5, 15, 2)
# Display the range items on the console
print(var_range1)
print(var_range2)
print(var_range3)
# Display the type on the console
print(type(var_range1))
print(type(var_range2))
print(type(var_range3))
The output of the above code reads as follows:
range(0, 10)
range(5, 15)
range(5, 15, 2)
<class 'range'>
<class 'range'>
<class 'range'>
The above shows a range()
function with different sets of arguments. The following shows the number of parameters this function takes:
- The first argument is the starting value of the sequence, this argument is optional.
- The second argument is the ending value of the sequence (or stop value), this argument is compulsory. Note: this number is exclusive, meaning that it will be included in the sequence.
- The third argument is the step size between each number in the sequence (incremental value).
Dictionary Data Type in Python
Python dictionary data type is used to store a collection of key:value pairs. The items in the dictionary are ordered (Python version 3.7 while the previous Python version is unordered), changeable, and do not allow duplicates and they are also indexed.
The Python dictionary is useful especially when it comes to representing things like sets of properties, mappings between items, and so on. The items or values in the dictionaries can be accessed using their keys. In Python, we use the following syntax to create a dictionaryvar_dict = {key_1: value_1, key_2: value_2, ....}
.
When declaring a dictionary, the keys can be any data type, including strings or integers, while the values can also be any of the Python data types, including strings, integers, or even other dictionaries.
In the following example we create a dictionary variable and assign keys and values in Python:
# Create a Python Dictionaries
var_dict = {
"item": "Mengo",
"qty": 5,
"category": "Vegetable",
"price": 2.99,
}
# Display the dictionary on the console
print(var_dict)
# Access specific item in the dictionary using its key
print(var_dict["item"])
print(var_dict["price"])
# Display its type on the console
print(type(var_dict))
The output of the above code reads as follows:
{'item': 'Mengo', 'qty': 5, 'category': 'Vegetable', 'price': 2.99}
Mengo
2.99
<class 'dict'>
Python Dictionary: Items are Ordered
In Python, dictionary items are ordered, which means that they are stored in a specific order and such order is preserved every time you are interacting with the dictionary items. The dictionary items will be ordered in the ways they are presented during the declaration.
For details, you can refer to the above example and its output as such data was displayed in the ways they have been defined.
Python Dictionaries: Items are Changeable
Python dictionaries are changeable, which means that users change, remove or add items after it has been created.
In the following example, we show you this in practice:
# Create a Python Dictionaries
var_dict = {
"item": "Mengo",
"qty": 5,
"category": "Vegetable",
"price": 2.99,
}
# Display the dictionary on the console before it changed
print("Before changed")
print(var_dict)
# Change the price by accessing it key
var_dict["price"] = 3.87
print()
# Display the dictionary on the console
print("After changed")
print(var_dict)
The output of the above code reads as follows:
Before changed
{'item': 'Mengo', 'qty': 5, 'category': 'Vegetable', 'price': 2.99}
After changed
{'item': 'Mengo', 'qty': 5, 'category': 'Vegetable', 'price': 3.87}
In the above code, we have changed the price value by accessing the key.
Python Dictionaries: Allow Duplicates
In Python, dictionary variables cannot store multiple items that are similar. This means dictionaries will not allow having two items with the same key.
Python will not trigger an error if you provide two items with the same key, instead, it will overwrite the existing one and always take the last one.
In the following example, we show you this in practice:
# Python Dictionaries do not allow duplicates
# Create a Python Dictionaries
var_dict = {
"item": "Mengo",
"qty": 5,
"qty": 10,
"category": "Vegetable",
"price": 2.99,
"price": 3.50,
}
# Display the dictionary on the console
print(var_dict)
The output of the above code reads as follows:
{'item': 'Mengo', 'qty': 10, 'category': 'Vegetable', 'price': 3.5}
In the above code, we intentionally created two prices with the same keys and two quantities (qty) with the same key as well but different values. Therefore the dictionary only takes the last one and overwrites the previous one.
Python Dictionaries: Items are Indexed
Python dictionaries are not indexed using index numbers such as 0,1,2 etc, instead, they are indexed based on their keys. There are several ways you can access the items in the dictionary and Python provides several methods to assist when dealing with dictionaries.
for example, you can use the get()
method to access the dictionary value using its key.
In the following example, we show you this in practice:
# Create a Python Dictionaries
var_car_origin = {
"BMW": "Germany",
"Audi": "Germany",
"Rolls Royce": "United Kingdom",
"Toyota": "Japan",
"Volvo": "Sweden",
"Lamborghini": "Italy",
"Mercedes-Benz": "Germany"
}
# Display the dictionary on the console
print(var_car_origin["BMW"])
print(var_car_origin["Volvo"])
print(var_car_origin.get("Rolls Royce"))
The output of the above code reads as follows:
Germany
Sweden
United Kingdom
None Data Type in Python
In Python, the None Type is used when we are declaring a variable with no value. To define such a variable we use the keyword None
after the assignment operator, this tells the compiler to define a variable with a null value.
Syntax of None type variable: var_name = None
In the following example, we create a variable and assign a null value using None
keyword in Python:
# Python None Type
# Create a Python variable and assign null value using None keyword
var_none = None
print(var_none)
print(type(var_none))
# following type are non None type
var_a = 0
var_b = ""
var_c = False
print(var_a)
print(var_b)
print(var_c)
print(type(var_a))
print(type(var_b))
print(type(var_c))
The output of the above code reads as follows:
None
<class 'NoneType'>
0
False
<class 'int'>
<class 'str'>
<class 'bool'>
Note: As shown in the above code, there is a difference between the None
, False
, 0
, or ""
(empty string). None is a data type of its own (NoneType) and only None can be None. Instead, they are Bool, int, and string while the variable with the None is None type.
Conclusion
In summary, in this tutorial, we have deeply discussed all the Python data types, and their importance, characteristics, and basic syntax was highlighted. Therefore, understanding Python data types will boost the developer’s performance in using the relevant variables and performing their coding operations effectively.