1

I am tryng to generate some arrays with random numbers and then put those arrays in another array one after another. but instead of putting them one after another my code is putting the last array generated in all the fields of the 2d array. Please help I cant identify the problem.

example for the code below: the inner loop makes an array with random number [1,0,2,3] then this array is put in another array where the index is the range of numbers in the first loop.

import random
arr=[0 for i in range(0,6)]
arr2=[]

for j in range(0,10):
    for l in range(0,6):
        arr[l]=random.randrange(0,4,1)
    print(arr)
    arr2.append(arr)

print(arr2)

output:

[0, 2, 2, 0, 0, 3]
[2, 0, 3, 1, 0, 1]
[2, 0, 0, 0, 3, 2]
[3, 1, 1, 0, 0, 3]
[3, 1, 2, 3, 0, 3]
[2, 3, 1, 0, 3, 1]
[3, 0, 2, 0, 2, 1]
[2, 2, 0, 1, 0, 0]
[1, 2, 1, 1, 3, 2]
[1, 0, 1, 3, 0, 3]
[[1, 0, 1, 3, 0, 3], [1, 0, 1, 3, 0, 3], [1, 0, 1, 3, 0, 3], [1, 0, 1, 3, 0, 3], [1, 0, 1, 3, 0, 3], [1, 0, 1, 3, 0, 3], [1, 0, 1, 3, 0, 3], [1, 0, 1, 3, 0, 3], [1, 0, 1, 3, 0, 3], [1, 0, 1, 3, 0, 3]]

enter image description here

Boseong Choi
  • 2,566
  • 9
  • 22
RAFIN KHAN
  • 65
  • 6
  • 3
    Post all information, including output, is the question, directly as text. – Carcigenicate Mar 14 '20 at 16:45
  • [2, 3, 0, 2, 2, 0] [2, 1, 1, 0, 0, 0] [0, 0, 1, 2, 3, 3] [0, 3, 1, 2, 1, 1] [1, 2, 1, 2, 3, 2] [3, 0, 1, 1, 1, 3] [1, 1, 3, 3, 2, 2] [0, 0, 0, 1, 3, 2] [0, 0, 0, 1, 0, 3] [1, 2, 3, 1, 0, 2] [[1, 2, 3, 1, 0, 2], [1, 2, 3, 1, 0, 2], [1, 2, 3, 1, 0, 2], [1, 2, 3, 1, 0, 2], [1, 2, 3, 1, 0, 2], [1, 2, 3, 1, 0, 2], [1, 2, 3, 1, 0, 2], – RAFIN KHAN Mar 14 '20 at 16:46
  • We prefer text output in a code block using `\`\`\`none` `\`\`\``. Try and not use images. – Maarten Bodewes Mar 14 '20 at 16:50
  • Also see [this](https://stackoverflow.com/questions/57593294/concatenation-of-the-result-of-a-function-with-a-mutable-default-argument/57593695#57593695) about the mayhem that can be caused by using the same object everywhere – ForceBru Mar 14 '20 at 16:52

1 Answers1

2

Welcome to Stack Overflow!

You're always appending the same array, when you change it afterwards - it changes all references to that array. You need to keep creating new arrays instead of using the old one:

import random

arr2=[]

for j in range(0,10):
  for l in range(0,6):
    arr=[0] * 6
    arr[l]=random.randrange(0,4,1)
  print(arr)
  arr2.append(arr)

print(arr2)

Even better:

import random

arr2=[]

for j in range(0,10):
  arr = [random.randrange(0,4,1) for _ in range(6)]
  print(arr)
  arr2.append(arr)

print(arr2)

Or even subjectively better:

import random

arr2 = [[random.randrange(0,4,1) for _ in range(6)] for _ in range(10)]
James Ashwood
  • 469
  • 6
  • 13
Omer Tuchfeld
  • 2,886
  • 1
  • 17
  • 24