0

I have initialize this list in python

distance_between_customers = [[None] * len(vehicle)] * len(vehicle)
print(distance_between_customers)

The result is exactly what I need: [[None, None, None], [None, None, None], [None, None, None]] .

Now, I like to change 'only' the pivot to zeros

for i in range(len(vehicle)):
    distance_between_customers[i][i] = 0
print(distance_between_customers)

The result I get is: [[0, 0, 0], [0, 0, 0], [0, 0, 0]]

But I like to get this result: [[0, None, None], [None, 0, None], [None, None, 0]]

I need a help please. Thank you in advance.

HassanDh
  • 17
  • 7
  • 3
    This is one of the classic blunders in Python. Your first list does not contain three lists. It contains three references to ONE list. When you change the first sublist, you're changing them all. You can use `distance_between_customers = [[None] * len(vehicle) for _ in range(len(vehicle))]`. – Tim Roberts May 08 '22 at 01:17

0 Answers0