Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if object is list of list in python?

Tags:

python

list

Is there any ways we can detect if an object is list in python using type(obj) --> list.

But how can we detect if the object is list of list of the form as:

[['a','b']['a','b'][][]]
like image 466
Nilesh Agrawal Avatar asked May 03 '13 21:05

Nilesh Agrawal


People also ask

How do you check if an object is not in a list Python?

“not in” operator − This operator is used to check whether an element is not present in the passed list or not. Returns true if the element is not present in the list otherwise returns false.

How do you check if an object is a list or a string Python?

The best way to checks if the object is a string is by using the isinstance() method in Python. This function returns True if the given object is an instance of class classified or any subclass of class info, otherwise returns False.

How do you check if a variable is a list in Python?

Check if Variable is a List with type() Now, to alter code flow programatically, 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.")


2 Answers

Use isinstance() to check for a specific type:

>>> isinstance([], list)
True

Use all() to test if all elements are of a certain type:

all(isinstance(elem, list) for elem in list_of_lists)

all() short-circuits; if any of the tests returns False, the loop is terminated and False is returned. Only if all but one element returns True does all() need to examine every element of the iterable.

like image 105
Martijn Pieters Avatar answered Oct 06 '22 02:10

Martijn Pieters


If you want to make sure that every item in your list is a list, you could do something like this:

if all(isinstance(i, list) for i in lst):
    # All of the items are lists
  • isinstance(i, list) is the better way of writing type(i) == type(list) or type(i) == list).
  • all() returns True if all of the items in the sequence are True. It'll return False if any aren't True.
like image 25
Blender Avatar answered Oct 06 '22 03:10

Blender