Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if an element of a list is a list (in Python)?

Tags:

python

If we have the following list:

list = ['UMM', 'Uma', ['Ulaster','Ulter']]

If I need to find out if an element in the list is itself a list, what can I replace aValidList in the following code with?

for e in list:
    if e == aValidList:
        return True

Is there a special import to use? Is there a best way of checking if a variable/element is a list?

like image 912
rishimaharaj Avatar asked Mar 18 '12 16:03

rishimaharaj


People also ask

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

Given an object, the task is to check whether the object is list or not. if isinstance (ini_list1, list ): print ( "your object is a list !" )

How do you check if an element is a list equal in Python?

if len(set(input_list)) == 1: # input_list has all identical elements.


3 Answers

Use isinstance:

if isinstance(e, list):

If you want to check that an object is a list or a tuple, pass several classes to isinstance:

if isinstance(e, (list, tuple)):
like image 142
warvariuc Avatar answered Oct 19 '22 14:10

warvariuc


  1. Work out what specific properties of a list you want the items to have. Do they need to be indexable? Sliceable? Do they need an .append() method?

  2. Look up the abstract base class which describes that particular type in the collections module.

  3. Use isinstance:

    isinstance(x, collections.MutableSequence)
    

You might ask "why not just use type(x) == list?" You shouldn't do that, because then you won't support things that look like lists. And part of the Python mentality is duck typing:

I see a bird that walks like a duck and swims like a duck and quacks like a duck, I call that bird a duck

In other words, you shouldn't require that the objects are lists, just that they have the methods you will need. The collections module provides a bunch of abstract base classes, which are a bit like Java interfaces. Any type that is an instance of collections.Sequence, for example, will support indexing.

like image 23
Katriel Avatar answered Oct 19 '22 14:10

Katriel


Expression you are looking for may be:

...
return any( isinstance(e, list) for e in my_list )

Testing:

>>> my_list = [1,2]
>>> any( isinstance(e, list) for e in my_list )
False
>>> my_list = [1,2, [3,4,5]]
>>> any( isinstance(e, list) for e in my_list )
True
>>> 
like image 10
dani herrera Avatar answered Oct 19 '22 14:10

dani herrera