-1

I'm very new to python, only practiced it for around a week, so I don't really know much about it.

list = []
for i in range(10):
    r=random.randint(1,100)
    if r not in list: 
        list.append(r)
print(list)
print(len(list))

The issue is that the length of the list can sometimes be 10, 9, or even 8 sometimes. How do I make 10 random numbers, that don't repeat, with a fixed length?

bad_coder
  • 11,289
  • 20
  • 44
  • 72
Oded
  • 9
  • 2

4 Answers4

1

Are you sure you don't just want to build a set?

This will eliminate duplicates without the explicit check for inclusion.

from random import randint

s = set()
while len(s) < 10: s.add(randint(1, 100))

Or simply:

import random

random.sample(range(1, 100), k=10)
Chris
  • 26,361
  • 5
  • 21
  • 42
0

This should work:

import random
list = []
while len(list)<10:
    r=random.randint(1,100)
    if r not in list:
        list.append(r)
print(list)
print(len(list))
gphull
  • 78
  • 5
  • Would you mind adding a bit of explanation? Code-only answers aren't very informative to people who don't already know the answer. – CrazyChucky Aug 27 '22 at 20:17
0

You can use random.sample which takes in a population and k which is the number of unique elements you want to sample from the population.

>>> import random
>>> random.sample(range(1,100), 10)
[19, 92, 65, 16, 44, 68, 82, 56, 71, 7]
erip
  • 16,374
  • 11
  • 66
  • 121
-1

I don't know your doubt/angle for this problem.

If you just want to solve, use numpy:

import numpy as np
# 12345 is a random_state (allows reproducibility)
# remove if you want to generate different numbers
# from different iterations
rng = np.random.default_rng(12345)
rints = rng.choice(np.arange(1, 100), 10, replace=False)
rints

Considering a student perspective:

  1. Your code do this:
for 10 runs:
    pick one random integer from 1 to 99
        if the integer is not in list
            append it
        else
            do nothing
            #That's why you're getting 8 or 9 numbers from some runs.

You need to "compensate" when you draw a repeated integer:

import random 
my_list = [] 
n = 0
iters = 1
while n < 10: 
    r=random.randint(1,100) 
    if r not in my_list: 
        my_list.append(r) 
        print(my_list)         
        print(len(my_list))
        print(iters)
        n += 1
    iters += 1
  1. You shouldn't use "list" to assign variables. Some words are reserved in python [1]. Being more specific, "list" isn't a keyword, just a build-in function [2], but assign a value for it can be considered an anti-pattern [3].

[1] https://docs.python.org/3/reference/lexical_analysis.html#keywords

[2] https://docs.python.org/3/library/functions.html#func-list

[3] https://frostyx.fedorapeople.org/The-Little-Book-of-Python-Anti-Patterns-1.0.pdf