I am trying to make there be a list within a list and then edit the number within the list within the list

Viewed 56

I have tried doing a battleships programme where the computer randomly generates the positions of the 1 sized ships, but when I tried changing the individual integers to 2 in the grid made up of 8 lists within a large list, but was unable to do anything with the lists.

Here is the code I have tried so far:

import random

ocean = []

for index_1 in range(0, 8):
  row = []
  for index_2 in range(0, 8):
    row.append(0)
  ocean.append(row)

for index_3 in range(0,8):
  xAxis = []
  xAxis.append(random.randint(0,8))
  yAxis = []
  yAxis.append(random.randint(0,8))

nums = range(0,8)

for num in nums:
  [ocean[yAxis[num]]] = 2
2 Answers

Welcome to stack overflow. A few things I will point out:

In this segment:

for index_3 in range(0,8):
  xAxis = []
  xAxis.append(random.randint(0,8))
  yAxis = []
  yAxis.append(random.randint(0,8))

You loop and set xAxis and yAxis to empty list every time before you add a random int to the lists. Because of that, at the end of the loop, yAxis and xAxis only have one element.

To fix it, move xAxis = [] and yAxis = [] before the loop.

Additionally, randint(0, 8) includes both start and end in the return. You want randint(0, 7) so you don't get index out of range.

Next:

nums = range(0,8)

for num in nums:
  [ocean[yAxis[num]]] = 2

Here, yAxis only has one element, but even after you fix it, it should throw an error. What you would be trying to do is unpacking a list, but 2 is not a list.

[ocean[yAxis[num]]] = 2 would be the same as writing ocean[yAxis[num]], = 2. Now that , looks out of place. So what you are probably looking for is ocean[yAxis[num]] = 2.

But, being as ocean is [[0,0,0,0,..],[0,0,0,0,...],...], you probably don't want to set one of it's elements to 2. You want to set one of the nested lists's elements to 2.

Maybe something like this:

nums = range(0,8)

for num in nums:
  ocean[xAxis[num]][yAxis[num]] = 2

so ocean will look like:

[
    [0,0,2,0,0,2,0,0],
    [0,0,2,0,0,0,0,0],
    ...
]

As @IamFr0ssT already pointed out, you are emptying out xaxis and yaxis at every iteration. and assigning ships to ocean with only y axis.
Correcting above, below is a complete code.

import random

ocean = [[0 for _ in range(8)] for _ in range(8)]
ship_locations = [[random.randint(0,8-1),random.randint(0,8-1)] for _ in range(0,8)]

for location in ship_locations:
  ocean[location[0]][location[1]]=2

print(ocean)

Related