How Do You Find the Data Type of an Array in Python?

//

Larry Thompson

To determine the data type of an array in Python, you can use the type() function. This function returns the type of an object.

However, when dealing with arrays, it’s important to note that Python arrays are not a built-in data type. Instead, we have lists which are more commonly used to represent arrays in Python.

To find the data type of a list (or an array), you simply pass the list as an argument to the type() function. Let’s take a look at an example:

Example 1:

“`python
my_list = [1, 2, 3, 4, 5]
print(type(my_list))
“`

In this example, we have a list called `my_list` containing integers. By using the type() function and passing `my_list` as an argument, we can determine its data type.

The output of this code will be:

<class ‘list’>

As you can see from the output above, the type() function returns ``, confirming that `my_list` is indeed a list data type.

Now let’s explore another scenario where our list contains elements of different data types:

Example 2:

“`python
mixed_list = [1, “Hello”, True]
print(type(mixed_list))
“`

In this example, our list called `mixed_list` contains elements of different data types such as integers (`1`), strings (`”Hello”`), and boolean values (`True`).

Similar to Example 1, we again get `` as the output. This indicates that regardless of the data types present within the list, the overall data type of the list remains as a list.

Now, let’s say you want to determine the data type of each individual element within a list. In such cases, you can use a loop to iterate over each element and apply the type() function:

Example 3:

“`python
my_list = [1, “Hello”, True]

for item in my_list:
print(type(item))
“`

In this example, we iterate over each element in `my_list` and print its respective data type.

<class ‘int’>

<class ‘str’>

<class ‘bool’>

As you can see from the output above, we are able to determine the data type of each individual element within the list using the type() function.

In conclusion, finding the data type of an array (or a list) in Python is as simple as using the type() function. Remember that regardless of the elements contained within a list, its overall data type will always be considered as a list. If you need to determine the data type of each individual element within a list, you can use a loop to iterate over each element and apply the type() function accordingly.

Discord Server - Web Server - Private Server - DNS Server - Object-Oriented Programming - Scripting - Data Types - Data Structures

Privacy Policy