The thing whith the "id" | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

The thing whith the "id"

Can somebody tell me how does id wors in Python? By example, id([123,456]) == id([456,123]) will be True or False?

15th Mar 2024, 8:33 PM
AiVolt
AiVolt - avatar
2 Answers
+ 6
AiVolt your example prints True. print(id([123,456])==id([456,123])) Output True Step by step, here what I understand Python does: 1. Create a new list [123,456]. 2. Pass the list into the id() method. 3. Hold the return value of id(). 4. At this point, since there are no other references to list [123,456], free the memory and id. 5. Create a new list [456,123]. It gets the same id as the prior list argument, since that id slot was freed for re-use. 6. Pass the list into the id() method. 7. Hold the return value of id(). 8. Free the id used by [456,123]. 9. Compare return values. 10. Print the result, True. You can prevent Python from freeing the lists by making them persist beyond the id() method calls. Do this by adding a variable reference. Python will not free an id as long as there is at least one reference in use. Then their ids will be different and their equality comparison will be False. Below is an example that makes the first list persist: print(id(c := [123,456])==id([456,123])) Output False
15th Mar 2024, 9:39 PM
Brian
Brian - avatar
17th Mar 2024, 12:07 AM
Rain
Rain - avatar