+ 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")
11 Answers
+ 2
Get all related queries
Thanks Jayakrishna🇮🇳 Runtime Terror
https://code.sololearn.com/cO18QXuPUvSD/?ref=app
+ 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))
+ 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.
"""
+ 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.
0
though
a==b
id(a)!=id(b)
As it is assigned seperate number in memory allocation.
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.
0
Runtime Terror Could you please explain the last two sentences of your comment? I don't understand the difference between the two.
0
Check
Print (id(a))
- 1
Ex.