How to check if a list item is a list (in Python)?

If we have the following list:

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

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

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

Is there any special import to use? Is there a better way to check if a variable / element is a list?

+48
python
Mar 18 2018-12-18T00:
source share
3 answers

Use isinstance :

 if isinstance(e, list): 

If you want to verify that the object is a list or tuple, pass a few classes to isinstance :

 if isinstance(e, (list, tuple)): 
+91
Mar 18 2018-12-18T00:
source share
  • Determine which list properties you want items to have. Do they need to index? Sliceable Do they need a .append() method?

  • See the abstract base class that describes this particular type in collections .

  • Use isinstance :

     isinstance(x, collections.MutableSequence) 



You may ask: "Why not just use type(x) == list ?" You should not do this because then you will not support what looks like lists. And part of the Python mentality is duck print :

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

In other words, you should not require the objects to be list s, just that they have the methods you need. The collections module provides a bunch of abstract base classes that look a bit like Java interfaces. Any type that is an instance of collections.Sequence , for example, will support indexing.

+20
Mar 18 2018-12-18T00:
source share

The expression you are looking for could 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 >>> 
+6
Mar 18 '12 at 16:27
source share



All Articles