0

I'm using Python 3.6.9, I'm confused, why in the code below do I get 2 toggling ids?

In [1]: [id([None]*3) for _ in range(5)] 
   ...:                                                                                                                                                                                                            
Out[1]: 
[140161829603400,
 140161829654920,
 140161829603400,
 140161829654920,
 140161829603400]

From my understanding when creating lists in the loop all lists will have the same IDs, or if done right, you can get independent lists with different IDs. How to explain this behavior?

juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172
tsh
  • 877
  • 8
  • 12
  • Do [this](https://stackoverflow.com/questions/8174723/dictionary-creation-with-fromkeys-and-mutable-objects-a-surprise) and [this](https://stackoverflow.com/questions/11509721/how-do-i-initialize-a-dictionary-of-empty-lists-in-python) help? – re-za Mar 20 '22 at 18:52
  • @re-za The main objective is to understand the behavior) – tsh Mar 20 '22 at 19:07
  • This behavior seems to happen only when you call `id()` inside the original comprehension. Otherwise if you initialize the outer list and then do another comprehension to get the ids, they're all going to be different. – re-za Mar 20 '22 at 19:19
  • "From my understanding when creating lists in the loop all lists will have the same IDs" your understanding is not correct. – juanpa.arrivillaga Mar 20 '22 at 19:55
  • 1
    In any case, there isn't much to explain. `id` returns a value that is guaranteed to be unique *for the lifetime of the object*. The `list` objects you create in the list comprehension only survive for each iteration of the loop (after the `id` function returns a value, they cease to exist). Hence the `id` function is free to return the same ID, although, *it doesn't have to*. And *there is no reason you should expect it to* – juanpa.arrivillaga Mar 20 '22 at 19:58

0 Answers0