List saving values from last loop using Random at all positions

Asked

Viewed 39 times

0

Guys, I’m trying to create a list of random values inside other predefined lists. Then in the loop it returns me exactly 10 lines with 4 data with different values. But when it exits the loop and I send a print on all lines saved only the random values of the last loop in all indexes.

numbers = 10
x_tes2 = [[0,0,0,0]]*numbers


for key in range(0,numbers):
    x_tes2[key][0]=int(random.choice(year))
    x_tes2[key][1]=int(random.choice(km_driven))
    x_tes2[key][2]=str(random.choice(fuel))
    x_tes2[key][3]=str(random.choice(transmission))

    print(x_tes2[key][0:4])
print("\n")
print(x_tes2)

The output: Output

Does anyone know why?

  • 1

    When did you do that x_tes2 = [[0,0,0,0]]*numbers made all elements of the array x_tes2 reference the same array [0,0,0,0].

  • 1

    If you are wondering how to multiply lists in python have an answer I wrote a while ago trying to explain better.

1 answer

1


The problem is that when you create a shape array x_tes2 = [[0,0,0,0]]*numbers you’re multiplying the same list, copying and pasting it over and over again. That way, when you change any of the arrays all will be changed, because they all refer to the same list.

The best way for you to get to the result is to create an empty array, fill the list in the loop for and add this list to the main array, something like this:

numbers = 10
x_tes2 = []
for key in range(0, numbers):
    random_array = [int(random.choice(year)), int(random.choice(km_driven)), str(random.choice(fuel)), str(random.choice(transmission))]
    x_tes2.append(random_array)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.