+ 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?
2 Respuestas
+ 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
+ 1
AiVolt ,
Sort of related.
https://www.sololearn.com/discuss/3259635/?ref=app