'Generate a random list with different numbers
I am trying to generate a random list with 10 DIFFERENT numbers. This is what I have done so far:
from random import randint
my_list = []
i = 0
while i < 10:
random = randint(1, 25)
if random not in my_list:
my_list.append(random)
i = i + 1
else:
i = i
print(my_list)
But it does not work for some reason.
(UPDATED: My list will add the random number as a string, I need to add it as an integer)
You can use the code above, it works now.
Solution 1:[1]
use set
and then convert into list
, because list can contain duplicate elements.
example code is
from random import randint
my_set = set()
while len(my_set) < 10:
random = randint(1, 25)
my_set.add(str(random))
print(list(my_set))
Solution 2:[2]
You are converting the random number to a string (for some reason) before you add it to the list. Later, you check if the number is a value in the list, which it never will be, because you never add a number to the list. Here's a simpler demonstration of the problem:
>>> 3 in ['3']
False
Don't bother with strings (or the no-op i = i
).
from random import randint
my_list = []
i = 0
while i < 10:
r = randint(1, 25)
if r not in my_list:
my_list.append(r)
i = i + 1
print(my_list)
You can also use a set, which will ignore duplicates automatically.
my_set = {}
while len(my_set) < 10:
my_set.add(randint(1,25))
print(my_set)
Or use random.sample
, which you are reimplementing:
my_list = random.sample(range(1,26), 10)
Solution 3:[3]
Looks pretty straight-forward to me:
from random import randint
my_set = set()
while(len(my_set) < 10):
my_set.add(randint(0, 100))
my_list = list(my_set)
print(my_list)
My random output:
[96, 2, 35, 9, 87, 23, 88, 57, 91, 95]
Solution 4:[4]
you can also use random library:
import random
mylist = [random.randint(0,100) for item in range(10)]
Output: [4, 89, 40, 56, 37, 97, 73, 46, 10, 36]
random.randint(0,100) -> here specify the range of the random number
range(10) -> in your case 10 value
Hope it solves you problem
Solution 5:[5]
Here is a way to generate the random int of 10. You can also change the random number range by change the range in randint(). Moreover, you can also sum up the number in the lst by the last code I wrote.
from random import randint
count = 0
lst = []
for count in range(10):
lst.append(randint(0,100))
count += 1
print(lst)
print(sum(lst))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Prince Francis |
Solution 2 | chepner |
Solution 3 | |
Solution 4 | Community |
Solution 5 | Runyi Pang |