+ 1
type() function and comparison.
to check whether some data were lists or not, -- First, I did this, >>> a = [1,2,3] >>> type(a) == 'list' False I thought it would return True. But no! So I found an alternative, >>> str(type(a)) == "<class 'list'>" True So, it returned True, luckily. My question is, why didn't my first method work? đ (I thought it would) and is there some other ways (you know) to perform that same comparison?
9 Respostas
+ 5
You are not comparing like items, it may appear that way, but they are different.
a = [1,2,3] #list instantiated
print(type(a) == 'list') #list being compared to a string
print(type(a) == list) #list being compared to list
print(str(type(a)) == "<class 'list'>") #string being compared to string
print(list) #list class
+ 5
Don't use string for comparison:
print(type(a) == list) # true
Or if you wanna use a string then you can use the name magic method to get the actual name and not the class:
print(type(a).__name__ == "list") # true
+ 4
In first method, 'list' is a string, not type..
+ 4
type(<identifier>) is <typename>
type(a) is list # True
+ 4
type(a)( ) == [ ] # True
+ 3
Vitaly Sokol
hey, thanks for you help âș
but can you please explain,
>>> a = [1,2,4]
>>> type(a)()
[]
why did that happen? đ€
+ 2
M Tamim There 'a' is list.
And type(a) return list
then list() creates empty list which is output : []
+ 2
Jayakrishnađźđł
Oh, yeah! thanks, mate, I got it. đ
+ 1
Isinstance(a,list)