user12188239
user12188239

Reputation:

A different way to check the type of a list

list = [1,2,3]
print(type(list) == list) # Prints False

Other than changing the name of the list, is there another way to check the type of this list? (Because I have already referenced the list variable a lot of times in my code and it is pretty hard to change all of them.)

Upvotes: 2

Views: 69

Answers (2)

Guy
Guy

Reputation: 50809

This is because you are shadowing the built-in list

l = [1,2,3]
print(type(l) == list) # True

type(list) gives <class 'list'>, which is not [1,2,3].

You can use one of the options suggested by @ThierryLathuille, but the best practice will be renaming the list variable, you shouldn't use built-in names as variables names.

Upvotes: 2

Thierry Lathuille
Thierry Lathuille

Reputation: 24232

Your code justly returns False, as you replaced the original meaning of list by your list. You shouldn't use the names of Python builtins as variable names.

So, change the name of your list and it will work as expected.

If it's too late for that, as you suggest in the edit to your question, you can still access the original list with:

list = [1,2,3]
print(type(list) == __builtins__.list) 
# True

Or, the more recommended way, using isinstance instead of type(...) == ...:

print(isinstance(list, __builtins__.list))
# True

Upvotes: 4

Related Questions