0

I'm trying to enter a 100 number square into a 2D list https://i.stack.imgur.com/eSFiO.png with each list containing 10 numbers 1-10,11-20,21-30 and so on. This is my code so far but when I run it in my editor it just keeps running and eventually crashes without printing anything. Please explain to me what I am doing wrong. Thanks

number_square=[[],[],[],[],[],[],[],[],[],[]]
number_list=[1,2,3,4,5,6,7,8,9,10]
for row in number_square:
  for number in number_list:
    number_square.append(number)
    number_list.remove(number)
    number_list.append(number+10)  
print(number_square)
wjandrea
  • 28,235
  • 9
  • 60
  • 81
chaim8
  • 5
  • 3

3 Answers3

0

There are many changes required in your code. Good effort from your side on trying the code. I have modified the code and probably you can get the logic from it.

number_square=[[],[],[],[],[],[],[],[],[],[]]
number_list=[10,20,30,40,50,60,70,80,90,100]
for i in range(0,len(number_square)):
  for j in range(number_list[i]-9,number_list[i]+1):
    number_square[i].append(j)
Saurav Rai
  • 2,171
  • 1
  • 15
  • 29
0

Problems:

  1. Removing from number_list while iterating over it
  2. Appending to number_square instead of row

If I were you, I'd use a list comprehension with ranges instead:

number_square = [list(range(i, i+10)) for i in range(1, 101, 10)]

Due credit to Onyambu for suggesting something similar in a comment

wjandrea
  • 28,235
  • 9
  • 60
  • 81
0

That's because you aren't accessing the content of neither row nor number in the for loops. Here is a suggestion:

number_square=[[],[],[],[],[],[],[],[],[],[]]
number_list=[1,2,3,4,5,6,7,8,9,10]
i = 0
for row in number_square:
 for i in range(len(number_list)):
   row.append(number_list[i])
   number_list[i] += 10       
print(number_square)

Note that the first loop is equivalent to for each. In this syntax, you can't alter the value of the item in a list. In the second loop, I put a "traditional" for loop with range to alter the values in number_list.

Dharman
  • 30,962
  • 25
  • 85
  • 135