0

I have a nested list of 1's as follows:

rows = 8*"1".split()
nested_list = []

for i in range(8):
    nested_list.append(rows)

The above produces nested_list = [[1,1,1,1,1,1,1,1],[1,1,1,1,1,1,1,1]....x8]]

And I would like to change every other 1 to -1;

i.e I want the output to look like this: [[-1,1,1,1,1,1,1],[1,-1,1,1,1,1,1,1],[1,1,-1,1,1,1,1,1],[1,1,1,-1,1,1,1,1],...] - I hope you can see what is happening.

Here is my code to try and achieve this:

for i in range(len(nested_list)): 
    for j in range(i,len(nested_list)): 
        nested_list[i][i] = "-1" 
        break

However, this produces [[-1,-1,-1,-1,-1,-1,-1,-1],[-1,-1,-1,-1,-1,-1,-1,-1,-1],...x8]] But I don't understand why? My logic for the above code is that 'i' will iterate from 0 to 7; and for each iteration, j will be equal to 'i' and we then change the position nested_list[I][i] to -1, i.e. nested_list[1][1], then nested_list[2][2], then nested_list[3][3],..., nested_list[8][8], which is the diagonals of the 2-D array? Where is my logic incorrect?? Thanks!

  • You are appending the same list reference - not individual lists. Same data, same ref 8 times – Patrick Artner Sep 16 '21 at 12:19
  • `nested = [ [1 for _ in range(8)] for _ in range(8)]` + `for i in range(8): nested[i][i] = 42` – Patrick Artner Sep 16 '21 at 12:20
  • To do somethings in a quadratic 2d array you would only need to iterade 1 dim - you never use `j` so why create it?! Also remove the break after going down to 1 dim iteration – Patrick Artner Sep 16 '21 at 12:21
  • Hi Patrick, apologies I am quite new to this. I can't understand what changes I need to make to my code to make it work as desired. I understand your point about not using the 'j' and I see that I am appending the same list reference; is this what is causing the issue? Because as I change this list reference all of the appends change? – Patrick_Chong Sep 16 '21 at 12:41
  • I got it, never mind. Thanks for answer – Patrick_Chong Sep 16 '21 at 12:58

0 Answers0