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?
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 !" )
if len(set(input_list)) == 1: # input_list has all identical elements.
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)):
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?
Look up the abstract base class which describes that particular type in the collections
module.
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 list
s, 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.
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
>>>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With