Reputation: 19
Let's say I have a function that takes any number of arguments. Is there a way, except loops, to check if each of those arguments is a list?
def func(*args):
# check if all args are lists
I was trying any()
and all()
methods, but can't figure out if there is a way to use isinstance()
and type()
with them.
Upvotes: 1
Views: 660
Reputation: 138
There are many variants of this question:
In Python, the built-in functions type() and isinstance() help you determine the type of an object.
type(object) – Returns a string representation of the object’s type.
isinstance(object, class) – Returns a Boolean True if the object is an instance of the class, and False otherwise.
reference : Determining the type of an object
also check out this link for more details.
Upvotes: 0
Reputation: 2997
I like the answer above:
all_lists = all(isinstance(arg, list) for arg in args)
But note you can also do type hints in the newer versions of Python:
def func(*args:list):
# check if all args are lists
and you get some type checking from tools like Mypy
Upvotes: 0
Reputation: 6930
all(isinstance(arg, list) for arg in args)
Of course, there's a loop hidden in the generator expression; at the end of the day, there has to be some kind of loop..
Upvotes: 0
Reputation: 57114
Sure thing:
all_lists = all(isinstance(arg, list) for arg in args)
Upvotes: 5