Is A List A Data Type?

In Python there is a handy function to determine the data type of any variable, and it is aptly called type() . This function can help to assess whether a variable is of a certain data type to help you perform any type of computation on it.

The different data types available in Python are: int , float , str , dict , list , and tuple . Therefore, list is a data type and can be checked using the type() function.

What is type() in Python?

The type() function in Python helps to determine the data type of a variable. Here are some examples of what is returned when we use the type() function on certain values:

>>> type(1)
<class 'int'>
>>> type('1')
<class 'str'>
>>> type(.1)
<class 'float'>
>>> type({'a': 1})
<class 'dict'>
>>> type([1])
<class 'list'>
>>> type((1,))
<class 'tuple'>

The type() function helps to be able to perform operations on variable by type checking to determine we have the right data type to perform the operation on.

For example, if you were wanting to perform an operation on a list, but wanted to check the variable was of a list data type then you could write the following statement to check:

a = [1]
if type(a) == list:
    print("Yes!")
else:
    print("No")

# 'Yes!'

Note that to do a simple data type check on a variable, as shown in the example above, requires that the data type name by entered as the comparison without strings . The following would not work as you’d expect:

a = [1]
if type(a) == 'list':
    print("Yes!")
else:
    print("No")

# 'No'

Therefore, when doing any type checking, use the returned class name without the name being encapsulated in strings:

type('1') == str
# True
type(1) == int
# True
type(.1) == float
# True
type({'a': 1}) == dict
# True
type([1]) == list
# True
type((1,)) == tuple
# True

You will likely find yourself using these types of checks when writing functions in your Python code. As inputs cannot be trusted you will want to make sure they are of the data type expected in your code.

A recent example, I used where I had to check the data type of a variable for my function was in a recursive function . By checking the data type I was able to determine whether the function needed to be called again, or to return a value.

Summary

Lists are a data type in Python and can be checked by using the type() function like so: type([1]) == list .

There are a variety of different data types in Python, and the type() function is the easiest way to determine the type of any variable. It’s also very handy when creating your custom functions, as you can never be too sure of the type of input being passed through into your function’s parameters.

Photo of author
Ryan Sheehy
Ryan has been dabbling in code since the late '90s when he cut his teeth exploring VBA in Excel. Having his eyes opened with the potential of automating repetitive tasks, he expanded to Python and then moved over to scripting languages such as HTML, CSS, Javascript and PHP.