Python Forum

Full Version: Random nr. no repetition & printing multiple lines
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
First of all i apologize if a make any grammar mistakes English is not my native language.
I'm new to python and i have the following dilemma:
How do i print a random number set let's say 30 characters long without any repetitions.
This is the code that i have:
import random

mylist = []

for i in range(30):
    x = random.randint (1,100)
    if x not in mylist: mylist.append(x)

print (mylist)
This prints only one line and i want it to print 30, but the code also removes the duplicates and i end up with 27 or 26 numbers.
Hope you can help.
Thank you
change line 9 to select each item (in loop) and print the item:
example
for item in items:
    print(item)
There is random.sample(population, k) which "chooses k unique random elements from a population sequence or set." (use help(random.sample) for more information, press Q to quit help).

To get 30 unique items from range just:

random.sample(range(1, 100), 30)
Thank you for your responses.

Regarding what Larz60+ posted iv tried the code and it ended up giving 30 lines with the same numbers, i want the lines to differ.

Also i want to have the possibility to set the number of output lines.

Thank you
what I showed was an example,
you needed to replace with your list name:
for item in mylist:
    print(item)
Ok the changes you suggested:

import random
 
mylist = []
 
for i in range(10):
    x = random.randint (1,30)
    if x not in mylist: mylist.append(x)
 
for x in mylist:
    print(mylist)
This is the output:
[16, 4, 11, 15, 13, 14, 30, 18, 1]
[16, 4, 11, 15, 13, 14, 30, 18, 1]
[16, 4, 11, 15, 13, 14, 30, 18, 1]
[16, 4, 11, 15, 13, 14, 30, 18, 1]
[16, 4, 11, 15, 13, 14, 30, 18, 1]
[16, 4, 11, 15, 13, 14, 30, 18, 1]
[16, 4, 11, 15, 13, 14, 30, 18, 1]
[16, 4, 11, 15, 13, 14, 30, 18, 1]
[16, 4, 11, 15, 13, 14, 30, 18, 1]

Is there something that i miss?
Still - why not sample?

>>> import random
>>> random.seed(42)                                     # for replicating result, don't use it in actual code
>>> print(*random.sample(range(1, 100), 5), sep='\n')
82
15
4
95
36
You're still printing out the entire list each time!

should be:
>>> import random
>>> mylist = []
>>> for i in range(10):
...     x = random.randint (1,30)
...     if x not in mylist: mylist.append(x)
... 
>>> mylist
[15, 10, 3, 4, 25, 28, 27, 7]
>>> 
>>> for x in mylist:
...     print(x)
... 
15
10
3
4
25
28
27
7
>>>