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

Python

Python Problem Overview


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?

Python Solutions


Solution 1 - Python

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)):

Solution 2 - Python

  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.

Solution 3 - Python

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
>>> 

Solution 4 - Python

Probably, more intuitive way would be like this

if type(e) is list:
    print('Found a list element inside the list') 

Solution 5 - Python

you can simply write:

for item,i in zip(your_list, range(len(your_list)):

    if type(item) == list:
        print(f"{item} at index {i} is a list")

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionrishimaharajView Question on Stackoverflow
Solution 1 - PythonwarvariucView Answer on Stackoverflow
Solution 2 - PythonKatrielView Answer on Stackoverflow
Solution 3 - Pythondani herreraView Answer on Stackoverflow
Solution 4 - PythonSameerView Answer on Stackoverflow
Solution 5 - PythonKhyar AliView Answer on Stackoverflow