type() function and comparison. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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?

5th Sep 2020, 6:54 PM
M Tamim
M Tamim - avatar
9 Answers
+ 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
5th Sep 2020, 7:02 PM
Steven M
Steven M - avatar
+ 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
5th Sep 2020, 7:00 PM
Bagon
Bagon - avatar
+ 4
In first method, 'list' is a string, not type..
5th Sep 2020, 7:00 PM
Jayakrishna 🇮🇳
+ 4
type(<identifier>) is <typename> type(a) is list # True
5th Sep 2020, 7:29 PM
Ipang
+ 4
type(a)( ) == [ ] # True
5th Sep 2020, 8:00 PM
Vitaly Sokol
Vitaly Sokol - avatar
+ 3
Vitaly Sokol hey, thanks for you help ☺ but can you please explain, >>> a = [1,2,4] >>> type(a)() [] why did that happen? 🤔
6th Sep 2020, 2:13 PM
M Tamim
M Tamim - avatar
+ 2
M Tamim There 'a' is list. And type(a) return list then list() creates empty list which is output : []
6th Sep 2020, 4:58 PM
Jayakrishna 🇮🇳
+ 2
Jayakrishna🇮🇳 Oh, yeah! thanks, mate, I got it. 😊
6th Sep 2020, 8:52 PM
M Tamim
M Tamim - avatar
+ 1
Isinstance(a,list)
7th Sep 2020, 12:55 AM
Vision
Vision - avatar