0

My code is this. I want to add random numbers between 10-99 range. And when the code is running it gives such a problem. All of the four lines become the same. Also I try to give the numbers with input but in this time also the result was the same. Only the first given four integers take all the four lines.

import random

mx = [[0]*4] * 4

for i in range(4):

    for j in range(4):
        num = random.randint(10,99)
        mx[i][j] = num

#printing
for i in range(4):
    for j in range(4):
        print(mx[i][j],sep=" ",end=" ")
    print()

And it gives this problem

C:\Users\Username\Desktop>python file.py
89 98 99 67
89 98 99 67
89 98 99 67
89 98 99 67

What is problem in the source code?

  • 1
    Does this answer your question? [List of lists changes reflected across sublists unexpectedly](https://stackoverflow.com/questions/240178/list-of-lists-changes-reflected-across-sublists-unexpectedly) – Josh Clark May 04 '20 at 16:49

3 Answers3

1

Is the goal to just give you the 4x4 array, or also the presentation? The array could be achieved in a list comprehension like this:

[print([random.randint(10,99) for x in range(4)]) for y in range(4)]

Output:

[15, 57, 37, 90]
[40, 58, 39, 67]
[97, 38, 84, 86]
[14, 72, 50, 13]
dennisdee
  • 160
  • 10
  • If you wanted to get rid of the brackets and commas, you could unpack with an asterix in your print() like so: ```[print(*[random.randint(10,99) for x in range(4)]) for y in range(4)]``` – dennisdee May 04 '20 at 17:33
0

When you do mx = [[0]*4] * 4 you are not creating a list of lists with zeros. You are instead creating a list with references to the same list. Any change made to one of the lists will make a change to all of them.

Take a look at the related questions:
1. List of lists changes reflected across sublists unexpectedly
2. How can I make multiple empty lists in python?
3. How to create a list or tuple of empty lists in Python?

For 2D lists, there really isn't a 'clean' way of doing it. I would suggest using numpy.zeros or go with

 mx = [[0, 0, 0, 0], \
       [0, 0, 0, 0], \
       [0, 0, 0, 0], \
       [0, 0, 0, 0]]

Cibin Joseph
  • 1,173
  • 1
  • 11
  • 16
0

mx = [[0]*4] * 4 will only reproduce the same list 4 times. It will not create 4 individual lists like you intend to. You could try something like in the code below, to create individual lists inside a list.

mx = [None] * 4

for i in range(4):
    mx[i] = [None] * 4
    for j in range(5):
        num = random.randint(10,99)
        mx[i][j] = num
StubBurn
  • 66
  • 8