Explain Codes LogoExplain Codes Logo

Checking if type == list in python

python
type-checking
inheritance
polymorphism
Alex KataevbyAlex Kataev·Feb 1, 2025
TLDR

Check whether a variable is a list in Python using the isinstance() function:

# This line checks whether "my_var" decided to become a list when it grew up is_list = isinstance(my_var, list) # Returns True if my_var is a list

The Whens and Whys: Using isinstance()

The isinstance() function is your superpower when it comes to type checking in Python. That's because it’s able to peer through inheritance, unlike type(), which just can’t get past the veneer.

# Trust isinstance(), it sees through disguises! is_subclass = isinstance(object, classinfo)

Advantages of wielding isinstance()

  1. Subclass Sensitive: This function knows its way around a genealogical tree and handles polymorphism.
  2. Clarity: Makes your code read like an expertly-crafted mystery novel.
  3. Future-Proofed: isinstance() is your backup for when class hierarchies decide to play musical chairs.

A word of caution

Do not name your variables after built-in types. It’s like being Batman and naming your kid "Robin". Confusing, right? This is why:

list = [1, 2, 3] # You just shadowed the built-in list type is_list = isinstance(list, list) # Errors galore! Batman is not pleased.

Scanning for subclasses

In the mystical land of Python, you might stumble upon custom classes elegantly extending list. And like before, isinstance() triumphs.

class MyList(list): # Your very own list pass custom_list = MyList() # Flexing my inheritance with instanceof style is_list_instance = isinstance(custom_list, list) # True, MyList is a proud child of list

When Subclasses masquerade

But beware, it's a tricky world out there. Sometimes, things are not what they appear to be:

class NotAList(): # Behave like a list, but not a list. Heard of Impostor Syndrome? def __iter__(self): ... not_a_list = NotAList() # isinstance keeps it real, mate! This ain't a list. is_not_a_list = isinstance(not_a_list, list) # False

Hitchhiker's Guide to typing.List

Seen Python 3.4+? It introduced us to the typing module. It's the Swiss Army Knife of type complexity. Check this out:

from typing import List # Prof. Typing.List teaching isinstance() some new tricks is_typing_list = isinstance(my_var, List) # Type checking with typing.List