In this step, you will learn about type uniformity in Python. Type uniformity refers to the concept of ensuring that all elements within a collection, such as a list or dictionary, are of the same data type. This is important for maintaining consistency and avoiding unexpected errors in your code.
Let's start by creating a Python script to explore this concept.
-
Open the VS Code editor in the LabEx environment.
-
Create a new file named type_uniformity.py
in the ~/project
directory.
touch ~/project/type_uniformity.py
-
Open the type_uniformity.py
file in the editor.
Now, let's add some code to the type_uniformity.py
file to create a list with elements of the same type.
## Create a list of integers
int_list = [1, 2, 3, 4, 5]
## Print the list
print("List of integers:", int_list)
## Verify the type of each element
for item in int_list:
print("Type of", item, "is", type(item))
In this code, we create a list named int_list
containing only integer values. We then iterate through the list and print the type of each element using the type()
function.
Next, let's create a list with elements of different types.
## Create a list of mixed data types
mixed_list = [1, "hello", 3.14, True]
## Print the list
print("\nList of mixed data types:", mixed_list)
## Verify the type of each element
for item in mixed_list:
print("Type of", item, "is", type(item))
In this code, we create a list named mixed_list
containing integers, strings, floats, and booleans. We then iterate through the list and print the type of each element.
Now, let's run the script to see the output.
-
Open the terminal in the VS Code environment.
-
Navigate to the ~/project
directory.
cd ~/project
-
Run the type_uniformity.py
script using the python
command.
python type_uniformity.py
You should see output similar to the following:
List of integers: [1, 2, 3, 4, 5]
Type of 1 is <class 'int'>
Type of 2 is <class 'int'>
Type of 3 is <class 'int'>
Type of 4 is <class 'int'>
Type of 5 is <class 'int'>
List of mixed data types: [1, 'hello', 3.14, True]
Type of 1 is <class 'int'>
Type of hello is <class 'str'>
Type of 3.14 is <class 'float'>
Type of True is <class 'bool'>
As you can see, the int_list
contains elements of the same type (int
), while the mixed_list
contains elements of different types (int
, str
, float
, bool
).
Understanding type uniformity is crucial for writing robust and maintainable Python code. In the following steps, you will learn how to use the all()
function in conjunction with the type()
function to check for type uniformity in collections.