Just like in any other programming language, Python programming has some data types which are important in processing and managing data. One of the most popular forms of data structure is the list. However, there are times when we need to confirm whether a particular object is indeed a list before carrying out any list-related functions on it. This blog will teach you different methods of determining whether an object is a list in Python, or not.
- Confirming the type of an object using the function is instance
To verify whether an object is a list or not, the best approach is through the use of the function isinstance. This function tests if an object is of a certain class or if it is a child of that class.
Example:
# Define a list my_list = [1, 2, 3, 4] # Check if it is a list if isinstance(my_list, list): print("The object is a list.") else: print("The object is NOT a list.")
Output: The object is a list.
- Confirming the type of an object using the function type
Another approach is to use the type() function, or rather, one may elect to use the function the returns the type of an object. Nonetheless, this approach is not as preferable as the other since however it will not be very flexible compared to isinstance regarding subclasses.
Example:
# Define a list my_list = ["apple", "banana", "cherry"] # Check using type() if type(my_list) is list: print("The object is a list.") else: print("The object is NOT a list.")
Output: The object is a list.
- Handing Custom List Subclasses
If you define a custom class that extends the list class, isinstance() will still work with that class but type() will not.
Example:
class CustomList(list): pass # Create an instance of CustomList custom_list = CustomList([1, 2, 3]) # Using isinstance() print(isinstance(custom_list, list)) # Output: True # Using type() print(type(custom_list) is list) # Output: False
Now, we appears to assume that using “isinstance()” is the easier way to go to check list types.
- For Example, we try to check if someone uses a behavior that is list like.
Sometimes for checking if an object behaves like a list. It needs it to be an object which supports iteration and indexing.
Example:
is_list_like(obj): try: obj[0] # Try to access an index iter(obj) # Try to iterate over it return True except (TypeError, IndexError): return False # Test cases print(is_list_like([1, 2, 3])) # Output: True print(is_list_like("Hello")) # Output: True (strings are iterable) print(is_list_like(42)) # Output: False
This method is useful when working with duck typing.