Check if type is list in python

How to check if a variable is list in Python

In this tutorial, we are going to learn about how to check if a variable is list in Python with the help of examples.

Consider, that we have the following variable in our code:

Now, we need to check whether the above variable is a List.

To check if a variable is list or not, we can use the built-in type() function in Python.

The type() function takes the variable as an argument and returns the type of the following object.

nums = [1, 2, 3] if type(nums) == list: print('Variable is list') else: print('Variable is not a list')
  1. We have first initialized the variable with a list.
  2. Then we used the == operator to check if both values refer to the same object.

If it returns True then it prints the variable is list , if the variable is not a list then it returns False and prints Variable is not a list .

nums = (1, 2, 3) if type(nums) == list: print('Variable is list') else: print('Variable is not a list')

Using isinstance() function

Similarly, we can also use the isinstance() function in Python to check if a given variable is list.

The isinstance() function takes the two arguments, the first argument is object , and the second argument is type then It returns True if a given object is a specified type otherwise it returns False.

nums = [1, 2, 3] if isinstance(nums, list): print('Variable is list') else: print('Variable is not a list')

Источник

Python: Check if Variable is a List

Python is a dynamically typed language, and the variable data types are inferred without explicit intervention by the developer.

If we had code that needed a list but lacked type hints, which are optional, how can we avoid errors if the variable used is not a list?

In this tutorial, we’ll take a look at how to check if a variable is a list in Python, using the type() and isinstance() functions, as well as the is operator:

Developers usually use type() and is , though these can be limited in certain contexts, in which case, it’s better to use the isinstance() function.

Читайте также:  Timer script in javascript

Check if Variable is a List with type()

The built-in type() function can be used to return the data type of an object. Let’s create a Dictionary, Tuple and List and use the type() function to check if a variable is a list or not:

grocery_list = ["milk", "cereal", "ice-cream"] aDict = "username": "Daniel", "age": 27, "gender": "Male"> aTuple = ("apple", "banana", "cashew") # Prints the type of each variable print("The type of grocery_list is ", type(grocery_list)) print("The type of aDict is ", type(aDict)) print("The type of aTuple is ", type(aTuple)) 
The type of grocery_list is class 'list'> The type of aDict is class 'dict'> The type of aTuple is class 'tuple'> 

Now, to alter code flow programmatically, based on the results of this function:

a_list = [1, 2, 3, 4, 5] # Checks if the variable "a_list" is a list if type(a_list) == list: print("Variable is a list.") else: print("Variable is not a list.") 

Check if Variable is a List with is Operator

The is operator is used to compare identities in Python. That is to say, it’s used to check if two objects refer to the same location in memory.

The result of type(variable) will always point to the same memory location as the class of that variable . So, if we compare the results of the type() function on our variable with the list class, it’ll return True if our variable is a list.

Let’s take a look at the is operator:

a_list = [1, 2, 3, 4, 5] print(type(a_list) is list) 

Since this might look off to some, let’s do a sanity check for this approach, and compare the IDs of the objects in memory as well:

print("Memory address of 'list' class:", id(list)) print("Memory address of 'type(a_list)':", id(type(a_list))) 

Now, these should return the same number:

Memory address of 'list' class: 4363151680 Memory address of 'type(a_list)': 4363151680 

Note: You’ll need to keep any subtypes in mind if you’ve opted for this approach. If you compare the type() result of any list sub-type, with the list class, it’ll return False , even though the variable is-a list, although, a subclass of it.

This shortfall of the is operator is fixed in the next approach — using the isinstance() function.

Check if Variable is a List with isinstance()

The isinstance() function is another built-in function that allows you to check the data type of a variable. The function takes two arguments — the variable we’re checking the type for, and the type we’re looking for.

Читайте также:  Firefox поиск на php

Free eBook: Git Essentials

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

This function also takes sub-classes into consideration, so any list sub-classes will also return True for being an instance of the list .

Let’s try this out with a regular list and a UserList from the collections framework:

from collections import UserList regular_list = [1, 2, 3, 4, 5] user_list = [6, 7, 8, 9, 10] # Checks if the variable "a_list" is a list if isinstance(regular_list, list): print("'regular_list' is a list.") else: print("'regular_list' is not a list.") # Checks if the variable "a_string" is a list if isinstance(user_list, list): print("'user_list' is a list.") else: print("'user_list' is not a list.") 

Running this code results in:

'regular_list' is a list. 'user_list' is a list. 

Conclusion

Python is a dynamically typed language, and sometimes, due to user-error, we might deal with an unexpected data type.

In this tutorial, we’ve gone over three ways to check if a variable is a list in Python — the type() function, the is operator and isinstance() function.

Источник

Python: проверьте, является ли переменная списком

Python — это язык с динамической типизацией, и типы данных переменных выводятся без явного вмешательства разработчика.

Если бы у нас был код, который нуждался в списке, но не имел подсказок типа, которые не являются обязательными, как мы можем избежать ошибок, если используемая переменная не является списком?

В этой статье, мы будем разбирать то как проверить, является ли переменная списком в Python, используя функции type() и isinstance() , а также оператора is

Разработчики обычно используют type() и is , хотя они могут быть ограничены в определенных контекстах, в этом случае лучше использовать функцию isinstance() .

Проверьте, является ли переменная списком с type()

Встроенная функция type() может использоваться для возврата типа данных объекта. Давайте создадим Dictionary, Tuple и List и воспользуемся функцией type() , чтобы проверить, является ли переменная list или нет:

grocery_list = ["milk", "cereal", "ice-cream"] aDict = aTuple = ("apple", "banana", "cashew") # Prints the type of each variable print("The type of grocery_list is ", type(grocery_list)) print("The type of aDict is ", type(aDict)) print("The type of aTuple is ", type(aTuple)) 
The type of grocery_list is The type of aDict is The type of aTuple is

Теперь, чтобы программно изменить поток кода на основе результатов этой функции:

a_list = [1, 2, 3, 4, 5] # Checks if the variable "a_list" is a list if type(a_list) == list: print("Variable is a list.") else: print("Variable is not a list.") 

Проверьте, является ли переменная списком с оператором is

Оператор is используется для сравнения идентичностей в Python. Другими словами, он используется для проверки того, относятся ли два объекта к одному и тому же месту в памяти.

Читайте также:  Соединить элементы массива python

Результат type(variable) всегда будет указывать на то же место в памяти, что и класс этого variable . Итак, если мы сравним результаты функции type() в нашей переменной с классом list , он вернет True если наш variable является списком.

a_list = [1, 2, 3, 4, 5] print(type(a_list) is list) 

Поскольку для некоторых это может показаться неприемлемым, давайте проверим работоспособность этого подхода и сравним идентификаторы объектов в памяти:

print("Memory address of 'list' class:", id(list)) print("Memory address of 'type(a_list)':", id(type(a_list))) 

Теперь они должны вернуть тот же номер:

Memory address of 'list' class: 4363151680 Memory address of 'type(a_list)': 4363151680 

Примечание. Если вы выбрали этот подход, следует помнить о любых подтипах. Если вы сравните результат type() любого подтипа списка с классом list , он вернет False , даже если переменная — это список, хотя и является его подклассом.

Этот недостаток оператора is исправлен в следующем подходе — с помощью функции isinstance() .

Проверьте, является ли переменная списком с помощью isinstance()

Функция isinstance() — еще одна встроенная функция, которая позволяет вам проверять тип данных переменной. Функция принимает два аргумента — переменную, тип которой мы проверяем, и тип, который мы ищем.

Эта функция также принимает во внимание подклассы, поэтому любые подклассы list также будут возвращать True для экземпляра класса list .

Давайте попробуем это с помощью обычного list и UserList из фреймворка collections :

from collections import UserList regular_list = [1, 2, 3, 4, 5] user_list = [6, 7, 8, 9, 10] # Checks if the variable "a_list" is a list if isinstance(regular_list, list): print("'regular_list' is a list.") else: print("'regular_list' is not a list.") # Checks if the variable "a_string" is a list if isinstance(user_list, list): print("'user_list' is a list.") else: print("'user_list' is not a list.") 

Выполнение этого кода приводит к:

'regular_list' is a list. 'user_list' is a list. 

Вывод

Python — это язык с динамической типизацией, и иногда из-за ошибки пользователя мы можем иметь дело с неожиданным типом данных.

В этом руководстве мы рассмотрели три способа проверить, является ли переменная списком в Python — функцией type() , оператором is и функцией isinstance() .

Источник

Оцените статью