74

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?

4
  • 1
    possible duplicate of Test if a variable is a list or tuple
    – Matt Ball
    Commented Mar 18, 2012 at 16:24
  • 1
    Why do you need that? Are you trying to flatten your list?
    – Rik Poggi
    Commented Mar 18, 2012 at 16:28
  • 4
    Also: (1) Don't use list as variable name because it will shadow the built-in list(). (2) What should be the meaning of those round brackets?
    – Rik Poggi
    Commented Mar 18, 2012 at 16:29
  • @RikPoggi It's an exercise I'm trying. Originally we were asked to go through a standard list and return the count of elements which started with a capital "U". I wanted to see if I could expand it to search both the list and a sub-list for the same and return the count. So the procedure would return a count of four if the above list was the input. The () were typos. :-) Commented Mar 18, 2012 at 20:48

5 Answers 5

136

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

6
  • Abstract Baseclass reference (collections.MutableSequence is correct for list, but here is the main reference), for others who are reading this answer and curious: docs.python.org/library/…
    – ninjagecko
    Commented Mar 18, 2012 at 16:43
  • 2
    @ninjagecko yep that's the link in #2 =)
    – Katriel
    Commented Mar 18, 2012 at 16:53
  • 1
    @Alex your advice is technically correct, but it requires extra work that is not usually necessary. Why not just use isinstance(x, list)? It is straightforward, standard practice, and considered good practice. Plus, thinking about interfaces and ABCs is likely to stump a beginner programmer. A "better" solution is not best practice if it is too much trouble to use consistently.
    – alexis
    Commented Mar 18, 2012 at 17:53
  • @alexis isinstance(x, list) is not considered good practice, at least not in my books! It's OK if you're sure that you're never going to see any custom objects, but how much harder is it to do isinstance(x, collections.MutableSequence)?
    – Katriel
    Commented Mar 18, 2012 at 17:56
  • Well your authors probably know best, so I won't defend my point. But I've just been looking on the [python FAQ][1] and it just advises using isinstance with a class, or better yet avoiding it altogether.
    – alexis
    Commented Mar 18, 2012 at 18:14
11

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
>>> 
2
  • 1
    It's probably worth stressing that the variable named list in the question will hide the list type, meaning that most of the other answers posted here will fail if simply pasted in. (It's embarrassing how often I've been bitten by that one.) Commented Mar 18, 2012 at 16:32
  • 2
    +1 for using any() instead of some for-loop-if combination.
    – Christoph
    Commented Aug 26, 2013 at 14:04
3

Probably, more intuitive way would be like this

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

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.