search

How to check if a variable is a list in Python?

To check if a variable is a list in Python, you can use the isinstance() function or compare the type of the variable to the list type. Here's an example:

# Using isinstance()
x = [1, 2, 3]
if isinstance(x, list):
    print("x is a list")
else:
    print("x is not a list")

# Using type()
y = "Hello"
if type(y) == list:
    print("y is a list")
else:
    print("y is not a list")

In the above example, the isinstance() function is used to check if the variable x is an instance of the list type. If it is, it prints "x is a list"; otherwise, it prints "x is not a list".

Similarly, the type() function is used to compare the type of the variable y with the list type. If they are equal, it prints "y is a list"; otherwise, it prints "y is not a list".

Keep in mind that both isinstance() and type() checks will only identify variables that are specifically of the list type. If you want to include other types that behave like lists, such as tuples or other sequence types, you can modify the checks accordingly. For example, you can use isinstance(x, (list, tuple)) to check if the variable x is either a list or a tuple.

Related Questions You Might Be Interested