Tutorial

2 Ways to check if variable is a list in Python

7 min read

This article will explore ways to check if variable is a list in Python.

In Python programming, determining the type of a variable is often necessary. This is particularly important when writing functions that can handle multiple data types.  We’ll delve into two primary approaches: using type function and isinstance function in Python.

These methods are commonly used in Python to identify whether a variable is of a specific type, such as a list. We’ll discuss the use of these methods, and illustrate how to use each with practical examples. So, let’s dive right in!

Methods for Checking if a Variable is a List in Python

There are two common methods to check if a variable is a list in Python: Using either the functions type() or isinstance().

Using `type` to check if variable is a list in Python

To get the data type of an object, Python provides a handy function for us i.e. the type function. Given an object, type returns its data type.

The syntax for using type  method/function is as follows:

type(expression)

The type function expects a single argument (expression) that returns an object. It then returns the type of the value returned by the expression.

We can make use of the function type to check if the object a variable refers to is a list.

The following code example defines a function named isList that leverages type to check if its list.

def isList(var):
    if type(var) == list:
        return "contains a list"

    else:
        return "does not contain a list"

primes = [2, 3, 5, 7, 11, 13, 17, 19]
greet = "Hello World"
greet_chars = [char for char in greet]

print(f"variable 'primes' {isList(primes)}")
print(f"variable 'greet' {isList(greet)}")
print(f"variable 'greet_chars' {isList(greet_chars)}")

Code explanation

The custom function, isList, is defined with a single parameter; var, and checks if its type is equal to list.

If the type of var is list, the function isList returns the string message "contains a list", otherwise, it returns the string message "does not contain a list".

Our defined function is then tested with three variables; primes, greet, and greet_chars, to determine whether each variable contains a list. The result of the test is shown in the screenshot below:

output for using function type() to check if variable is a list in Python

While type method provides a basic check. Python provides the isinstance function for more flexibility. The next section will discuss how we can use isinstance method to check if a variable is a list in Python.

Using `isinstance` to check if variable is a list in Python

If we need to check if an object is an instance of a specific class or one of its subclasses, we can make use of the built-in function, isinstance.

It provides a more flexible and reliable way to determine if a variable is a list, compared to using the built-in function type.

Using isinstance is quite simple.

We need to pass the object we want to check, along with the type we want to check for.

The syntax of isinstance function we need is shown below:

isinstance(expression, object_type)

Where:

  • expression: Returns an object. isinstance will check if the return value of expression has a specific type.
  • object_type: The type we are checking expression for.

We will make use of a code example to illustrate how to make use of the function isinstance to check if a variable is a list.

In the example, we will adjust the isList (from the previous example) to make use of isinstance.

def isList2(var):
    if isinstance(var, list):
        return "contains a list"

    else:
        return "does not contain a list"

fib = [1, 1, 2, 3, 5, 8, 13, 21][1:6]
split_greet = "Hello World!".split()
empty_str = ""

print(f"variable 'fib' {isList2(fib)}")
print(f"variable 'split_greet' {isList2(split_greet)}")
print(f"variable 'empty_str' {isList2(empty_str)}")

Code Explanation

The function from the previous section, isList, is modified and named isList2. This modified function utilizes isinstance to check if a variable is a list.

Just like isList, isList2 takes a variable var as input, and returns a string message: either "contains a list" or "does not contain a list", depending on whether isinstance returns True or False respectively.

When we test isList2 with different variables (fib, split_greet, and empty_str), we get the following output:

output for using function isinstance() to check if variable is a list in Python

The isinstance() function not only checks if a variable is a particular type but also considers inheritance. That is, if we have a custom class that inherits from list, a variable of this custom class would be considered a list by isinstance(), but not by type().

Therefore, isinstance() is generally more flexible and recommended for checking the type of a variable.

More examples and usage of check if variable is a list in Python

Example: Calculating average

Let’s consider an example where we want to calculate the average of a list of numbers in Python. We use the isinstance() function to ensure that the input is indeed a list before performing the calculation.

def calculate_average(numbers):
  if isinstance(numbers, list):
    # Calculate average only if numbers is a list
    return sum(numbers) / len(numbers)
    
  else:
    print("Error: Invalid argument. Please provide a list of numbers.")

# Valid usage
average = calculate_average([3.2, 5.8, 6.0, 8.6, 2.6])
print(average)  # Output: 5.24

# Invalid usage (handled by the function)
calculate_average(5.8)

In this code, the function calculate_average calculates the average of a list of numbers. It first checks if the input numbers is a list using isinstance(). If numbers is a list, it calculates the average and returns it. Otherwise, it prints an error message.

The output below shows what happens when we test our calculate_average function with a list first, and then with a float number.

As expected, the function calculates the average for the list input and prints the error message for the float input.

output for using function isinstance() to check if var is a list when calculating average

Example: Creating a person’s information

Another practical example demonstrates how isinstance can be used to handle different types of input.

Here, we define a function create_person that takes two parameters and returns a dict object representing a person.

The parameters expected by our function are as follows:

  • name: The name of the person.
  • hobbies: The hobbies of the person.

We are particularly interested in the hobbies; since it will be a collection of things the person likes doing, we are expecting a list object. However, we have written the function to also accept a string of hobbies, separated by spaces.

See the code below for how we implemented the create_person function.

def create_person(name, hobbies):
  if isinstance(hobbies, str):
    return {
      "name": name,
      "hobbies": hobbies.split()  # Split string into a list of hobbies
    }

  if isinstance(hobbies, list):
    return {
      "name": name,
      "hobbies": hobbies          # hobbies is a list
    }

  raise TypeError("hobbies must be a string or a list")

# Example usage
person1 = create_person("Alice", "reading coding")
print(f"person1: {person1}")  # Output: {'name': 'Alice', 'hobbies': ['reading', 'coding']}

person2 = create_person("Bob", ["music", "gaming"])
print(f"person2: {person2}")  # Output: {'name': 'Bob', 'hobbies': ['music', 'gaming']}

try:
  person3 = create_person("Charlie", 42)

except TypeError as e:
  print(f"person3: Failed to create person because {e}")  # Output: Hobbies must be a string or a list

The function create_person uses isinstance to determine whether hobbies is a string or a list. However, if hobbies is neither a string nor a list, it raises a TypeError.

If hobbies is a string, it splits it into a list of hobbies. If it’s already a list, it includes it as is in the person’s information. So, if the hobbies input is either a str or a list, it creates a dictionary containing the person’s name and hobbies.

When we run the code, we get the following output:

output for using function isinstance() to check if var is a list in python when creating person dictionaries holding person name and hobbies

Conclusion

In conclusion, checking the type of a variable is a common task in Python, and the functions type and isinstance can be used to check if a variable is a list in Python.

However, using isinstance also considers if the instance is a subclass of the specified type. This allows us to write more flexible code that can handle different types of data.

If you liked this tutorial, please check out our easy-to-follow Python tutorials that will help to solve coding challenges, Or learn programming with the help of an online Python tutor.


Leave a Reply

Your email address will not be published. Required fields are marked *