Python | Check if a given object is list or not

Python | Check if a given object is list or not

In Python, checking if a given object is of a specific type is a foundational task. Here's a tutorial on how to determine if an object is a list:

Goal:

To verify if a given object is an instance of the list type.

1. Using type():

The type() function can be used to directly check the type of an object.

def is_list(obj): return type(obj) == list # Test obj1 = [1, 2, 3] obj2 = "Hello World" print(is_list(obj1)) # Output: True print(is_list(obj2)) # Output: False 

2. Using isinstance():

The isinstance() function is a more versatile choice, as it also works with subclasses (if you had a class derived from the list type).

def is_list(obj): return isinstance(obj, list) # Test obj1 = [1, 2, 3] obj2 = "Hello World" print(is_list(obj1)) # Output: True print(is_list(obj2)) # Output: False 

3. Using a Try-Except Block:

While less common for this particular task, using try-except can be a way to determine the type of an object based on the operations you can perform on it. For instance, trying to append an item to an object that isn't a list will raise an exception.

def is_list(obj): try: obj.append(None) obj.pop() return True except AttributeError: return False # Test obj1 = [1, 2, 3] obj2 = "Hello World" print(is_list(obj1)) # Output: True print(is_list(obj2)) # Output: False 

Note: This method actually modifies the object (by appending and then popping an element). It's more of a demonstration of the concept and is not recommended for typical use due to its side effects.

Summary:

To determine if an object is a list in Python, the isinstance() function is generally the best approach because of its clarity and versatility. The type() method is also commonly used when only checking against the exact type (and not subclasses). The try-except method can be useful in more complex scenarios where you might want to check for behaviors (capabilities) of an object rather than its explicit type, but care should be taken to avoid unintended side effects.


More Tags

save controllers post-increment ansible-handlers sql-order-by menu hostname amazon-rekognition self-extracting editor

More Programming Guides

Other Guides

More Programming Examples