0

I have an list like the following

line_37_data = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]

When I print line_37_data[0][0] , the value 0 is printed.

When I update the list as line_37_data[0][0] = 5, the list gets modified like below

[[5, 0, 0], [5, 0, 0], [5, 0, 0]]

How can I can update the value in the list based on the index ?

Note :- I don't use NumPy. This is pure plain Python without any libraries. I am using 2.7 and not Python 3

RandomWanderer
  • 701
  • 2
  • 12
  • 23

1 Answers1

3

If you pass in the same list as each element of your outer list, manipulating it will show in each place it appears. If you're just looking to fill a 2d list with zeros, list comprehension would be easy:

def generate_2d(h, w):
    return [[0 for x in range(w)] for y in range(h)]

array = generate_2d(3, 3)

# Format is array[y][x] based on names in function
array[0][0] = 5
array[1][2] = 7

assert array == [
    [5, 0, 0],
    [0, 0, 7],
    [0, 0, 0]]
Brett Beatty
  • 5,690
  • 1
  • 23
  • 37