Write a Python Function to Check if an Object is a List
Rustcode

Rustcode @rustcodeweb

About: Explore articles on web development for professional growth. Gain insights, tips, tricks, and resources for web tools and more.

Joined:
Nov 28, 2019

Write a Python Function to Check if an Object is a List

Publish Date: Aug 15
0 0

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.


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)
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Output:

True
False
False
False
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • isinstance(obj, list) checks if obj is 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)islist
Enter fullscreen mode Exit fullscreen mode

Example Usage:

print(is_exact_list([1,2,3]))# True
classMyList(list):
     pass
mylist = MyList()
print(is_exact_list(mylist))# False
Enter fullscreen mode Exit fullscreen mode

Output:

True
False
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • type(obj) is list checks 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})
Enter fullscreen mode Exit fullscreen mode

Output:

It's a list!
Not a list.
Not a list.
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • 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)
Enter fullscreen mode Exit fullscreen mode

Example Usage:

print(is_sequence([1,2,3]))# True
print(is_sequence((1,2,3)))# True
print(is_sequence("abc"))# False (excluded string)
Enter fullscreen mode Exit fullscreen mode

Output:

True
True
False
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • 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 0 total

    Add comment