very simple Python code, but why the variable n
has different IDs? How can I implement this function to get car
's dictionary name?
a = [{'a':['apple','animal']},{'b':['banana']},{'c':['class','car']}]
n = 0
while n < 3:
print(id(n))
for k in a[n].keys():
if 'car' not in a[n][k]:
n += 1
print(id(n))
else:
print(k)
break
break
The result of the code is:
140720577618304
140720577618336
an integer in Python is immutable. By doing n+=1
, you're not modifying the object called n
, you're overwriting the name to point to a new integer object.