Chetan Lohani
Chetan Lohani

Reputation: 1

Repeat of random number

I am trying to capture a random number without it repeating. the larger context is I am trying to get random items out of a list. Is there a way to capture random number enter image description herewhen looping without the variable getting repeated, without using pre defined functions? Thank You.

import random

random_var = 0
for i in range(0,10):
    random_var = random.randint(0,10)

Upvotes: 0

Views: 241

Answers (2)

Wizard.Ritvik
Wizard.Ritvik

Reputation: 11612

the larger context is I am trying to get random items out of a list.

You can use random.sample() for that:

import random

L = [1, 2, 3, 4, 5]

for i in random.sample(L, len(L)):
    print(i)

Assuming you are ok with it, random.shuffle() can be used to modify the list order:

import random

L = [1, 2, 3, 4, 5]

# L is now in haphazard order
random.shuffle(L)

# prints list in random order
for e in L:
    print(e)

I am trying to capture a random number without it repeating.

Try avoid random.choice() because you could end up with duplicates:

for i in range(len(L)):
    print(random.choice(L))

Sample output:

2
1
3
5
5  <-- repeat

Upvotes: 1

ytung-dev
ytung-dev

Reputation: 892

Try this:

import random

for i in random.sample(range(100), 10):
    print(i)
    ## print(l[i])

This will generate 10 number between 0 and 99.

Upvotes: 0

Related Questions