Write a Python Function to Check if an Object is a List
Sometimes, you need to know if a value in your Python program is really a list. Maybe you're building a function that should only work with lists, or you want to avoid errors when looping. Python makes it easy to check the type of an object. Here’s how you can write a simple, reusable function to check if something is a list, with clear explanations and examples.
Table of Content
Why Check if an Object is a List?
- Definition: Type checking means verifying whether a variable is a specific type, like a list, tuple, or string.
- Use Cases: Writing safe functions, avoiding runtime errors, and supporting flexible code that can handle different types.
- Benefits: Prevents bugs, makes your code more robust, and helps with debugging.
01. Using isinstance() (Recommended)
The isinstance() function is the most Pythonic way to check if an object is a list. It returns True if the object is a list, and False otherwise.
def is_list(obj):
return isinstance(obj, list)
Example Usage:
print(is_list([1, 2, 3])) # True
print(is_list("hello")) # False
print(is_list((1, 2, 3))) # False
print(is_list(42)) # False
Output:
True
False
False
False
isinstance(obj, list)checks ifobjis a list or a subclass of list.- Works even if you define your own class that inherits from
list. - Recommended for most real-world Python code.
02. Using type() for Exact Match
If you want to check that an object is exactly a list (not a subclass), you can use type():
def is_exact_list(obj):
return type(obj) is list
Example Usage:
print(is_exact_list([1, 2, 3])) # True
class MyList(list): pass
mylist = MyList()
print(is_exact_list(mylist)) # False
Output:
True
False
type(obj) is listchecks for the exact type, not subclasses.- Use this if you want to exclude custom list-like classes.
03. Function Examples and Outputs
Here’s a function that prints a message based on the type of the input:
def describe_object(obj):
if isinstance(obj, list):
print("It's a list!")
else:
print("Not a list.")
describe_object([10, 20])
describe_object("Python")
describe_object({'a': 1})
Output:
It's a list!
Not a list.
Not a list.
- The function uses
isinstance()for flexible type checking. - Helps you debug or branch your code based on input type.
04. Handling Other Sequence Types
If you want your function to work with any sequence (like lists, tuples, or strings), you can check for collections.abc.Sequence:
from collections.abc import Sequence
def is_sequence(obj):
return isinstance(obj, Sequence) and not isinstance(obj, str)
Example Usage:
print(is_sequence([1, 2, 3])) # True
print(is_sequence((1, 2, 3))) # True
print(is_sequence("abc")) # False (excluded string)
Output:
True
True
False
- This approach is useful if you want to accept lists and tuples, but not strings.
- Gives your code more flexibility for different sequence types.
05. Comparison Table: Ways to Check for a List in Python
| Method | Checks Subclasses | Checks Only Lists | Best For |
|---|---|---|---|
| isinstance(obj, list) | Yes | No | General use, flexible code |
| type(obj) is list | No | Yes | Exact type match |
| collections.abc.Sequence | Yes | No | Accepting lists, tuples, etc. |
Conclusion
Checking if an object is a list in Python is simple and reliable. Use isinstance(obj, list) for most cases, or type(obj) is list if you want to be strict. For even more flexibility, check for sequence types using collections.abc.Sequence. This helps you write safer, more robust, and more flexible Python code.
Comments
Post a Comment