0

Now I'm refactoring some code and I found something weird.

I thought the following 2 expressions were exactly same:

list1 = [[0.00] * 5 for _ in range(5)]
list2 = [[0.00] * 5] * 5

I can see they make same results by running:

print(list1 == list2)

or

import numpy as np
print(np.array(list1).shape == np.array(list2).shape)

But in the project I'm revising, list2 doesn't work. When I use it, it raises 'Index out of range'.

Please tell me if 'list1 == list2' as I said, or if I'm wrong about that.

Thanks in advance.

P.S. I can use numpy.zeros() or some other things, but I'm really curious.

cmaher
  • 5,100
  • 1
  • 22
  • 34
  • 5
    You do not want to use the second approach, it creates 5 references to the same list – user3483203 Apr 21 '18 at 16:02
  • 1
    They're equal, but they won't behave the same. Also you don't show a [mcve] of the code that errors. – jonrsharpe Apr 21 '18 at 16:02
  • Since they _are_ equal, there’s a good chance the error you’re encountering is related to code not shown in the question. For example, they would behave differently if the sublists are mutated. – Michal Charemza Apr 21 '18 at 16:07
  • 1
    To see the difference, compare the results of `map(id, list1)` and `map(id, list2)`. (Or `list(map(id, list1))` and `list(map(id, list2))` if you are using Python 3.) – chepner Apr 21 '18 at 16:09

0 Answers0