-3

Please if you know how to solve this: I need to add nested lists, each list with randomly generated numbers, but within the same range. If I run my code like it is, it adds nested lists, each list with the correct length of 6 numbers, but the problem is that all numbers in the lists are identical! the output is like that:

[
    [27, 2, 23, 12, 9, 2, 28, 31],
    [27, 2, 23, 12, 9, 2, 28, 31],
    [27, 2, 23, 12, 9, 2, 28, 31],
    [27, 2, 23, 12, 9, 2, 28, 31]
]

How can I manage to generate new numbers each time I call the function in the for loop?

lottery_numbers = []
numbers_list = []

def num_generator():
   for num in range(0, 2):
      random_number = random.randint(1, 40)
      numbers_list.append(random_number)
      lottery_numbers.append(numbers_list)
  

for number in range(0, 4):
  num_generator()
Daniel Walker
  • 6,380
  • 5
  • 22
  • 45
  • 2
    Your function also has the very strange behavior of adding 2 new entries (in both `numbers_list` and `lottery_numbers`) each time it is run. "correct length of 6 numbers" needs re-evaluation =). Your displayed output doesn't match the code, it would be 8x8, not 4x8. – Cireo Nov 18 '20 at 01:29

2 Answers2

3

assuming you want 4 nested lists in one list each with a length of 6...

import random

x = [[random.randint(1,40) for i in range(6)] for i in range(4)]

print(x)
[
    [21, 41, 22, 14, 35, 0], 
    [13, 31, 25, 19, 35, 27], 
    [36, 29, 40, 37, 47, 49], 
    [12, 19, 5, 27, 48, 27]
]

Using a list comprehension we iterate 4 times, returning another randomly generated list (nested list comps)

Ironkey
  • 2,568
  • 1
  • 8
  • 30
1

I tried to keep your code as much as possible but i think this is what you intended to do.

import random

lottery_numbers = []


def num_generator():
    numbers_list = []
    for num in range(0, 6):
        random_number = random.randint(1, 40)
        numbers_list.append(random_number)
    lottery_numbers.append(numbers_list)
  

for number in range(0, 4):
    num_generator()


print (lottery_numbers)

[[39, 8, 3, 35, 20, 11], [30, 38, 37, 22, 18, 8], [24, 13, 3, 20, 15, 24], [33, 24, 2, 38, 9, 14]]

bmjeon5957
  • 291
  • 1
  • 10