-1

I want to have a sub-list inside another which return the number of the index of the bigger list summed with the index of the little one.

Anyone with a explanation and the solution ?

def function():
  liste1 = [0] * 10
  liste2 = liste1 * 10
  i = 0
  while i < 10:
    j = 0 
    while j < 10:
      liste1[j] = i
      j += 1
    liste2[i] = liste1
    i += 1
  print(liste2)

function()

First, I tried this code but it return [[9,9,9,9,9,9,9,9,9,9],[9,9,9...

Yohann DCz
  • 21
  • 5

2 Answers2

0

I found ! The sublist must be reset for each turn and we sum up the j index to the i before we store them in the sublist at index j.

def function():
  liste1 = [0] * 10
  liste2 = [liste1] * 10
  i = 0
  while i < 10:
    j = 0 
    liste1 = [0] * 10
    while j < 10:
      liste1[j] = i + j
      j += 1
    liste2[i] = liste1
    i += 1
  print(liste2)

function()
Yohann DCz
  • 21
  • 5
0

you can do this more cleanly using list comprehension

l1 = [0]*10
l2 = [l1]*10
print([[i+j for j in range(len(l))] for i,l in enumerate(l2)])

which returns the list [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], [2, 3, 4, 5, 6, 7, 8, 9, 10, 11], [3, 4, 5, 6, 7, 8, 9, 10, 11, 12], [4, 5, 6, 7, 8, 9, 10, 11, 12, 13], [5, 6, 7, 8, 9, 10, 11, 12, 13, 14], [6, 7, 8, 9, 10, 11, 12, 13, 14, 15], [7, 8, 9, 10, 11, 12, 13, 14, 15, 16], [8, 9, 10, 11, 12, 13, 14, 15, 16, 17], [9, 10, 11, 12, 13, 14, 15, 16, 17, 18]]

Tr3ate
  • 138
  • 5