+ 5

What is id(a) in Python? How does this code perform? Identity function

a,b=[1,2],[1,2] if id(a)==id(b): print ("y") else: print("n")

1st Jul 2021, 2:04 PM
Zahed Shaikh
Zahed Shaikh - avatar
11 Answers
1st Jul 2021, 3:38 PM
Zahed Shaikh
Zahed Shaikh - avatar
+ 6
id(object) - identity function in python which require an object as argument. The id() function returns an unique identity number of argumented object which is a reference to memory location of that object. there 2 lists a,b are mutable objects and have different IDs in memory. so if condition becomes false and else part get executed and prints "n". check : print(id(a)) print(id(b))
1st Jul 2021, 2:25 PM
Jayakrishna 🇮🇳
+ 4
Zahed Shaikh a==b compares contents but id(a), id(b) returns reference number which is different. Calvin Thomas all mutable object are will have different ID's .(if they created new) Like list,int, dict,... But all immutable objects will have same reference values if they have same values .. immutable objects like tuple,strings. Ex: a=(1,2) b=(1,2) print (id(a)) print (id(b)) print( id(a)==id(b)) #true s1="abc" s2="abc" print(id(s1)==id(s2)) """ from above sample example posted links code, (@Zahed's) you get true for all , if a,b are tuples, immutable objects... also if a,b are lists and when you assign a=b ,now b reference is assigned to a so a,b will point to same reference. and also changes in one will reflect in other also. """
1st Jul 2021, 5:54 PM
Jayakrishna 🇮🇳
+ 2
Runtime Terror and Jayakrishna🇮🇳 Thank you for your great explanations. @Runtime Terror I guess that you had meant this code: return len(list1) == len(list2) and all(list1[i] == list2[i] for i in range(len(list1))) So the "==" operator compares the contents of the objects in the memory locations and the "is" operator compares just the ids.
2nd Jul 2021, 2:38 AM
Calvin Thomas
Calvin Thomas - avatar
0
though a==b id(a)!=id(b) As it is assigned seperate number in memory allocation.
1st Jul 2021, 2:33 PM
Zahed Shaikh
Zahed Shaikh - avatar
0
Jayakrishna🇮🇳 When do python objects share the same reference? I've seen this many times, but I can't recall any of those instances.
1st Jul 2021, 2:48 PM
Calvin Thomas
Calvin Thomas - avatar
0
Runtime Terror Could you please explain the last two sentences of your comment? I don't understand the difference between the two.
1st Jul 2021, 4:34 PM
Calvin Thomas
Calvin Thomas - avatar
0
Check Print (id(a))
3rd Jul 2021, 8:56 AM
Zeddy Sunny Zulu
Zeddy Sunny Zulu - avatar
- 1
Ex.
5th Jul 2021, 9:15 AM
Apd El Gfor Mohmed
Apd El Gfor Mohmed - avatar