umutberkbilgic
umutberkbilgic

Reputation: 62

Python: Preventing elements being appended to the same list over and over

I was working on my first OOP project, it is a random number generator, that generates a number of random numbers in a given range:

import random
import math

resList=[]

class randomInRange:
    def getRandom(self, start, end, quantity):
        for i in range(quantity):
            selList = range(start, end)
            resNum = random.choice(selList)
            resList.append(resNum)

        return (resList)

RR=randomInRange()

Then, I would type this in the Python Shell:

    (RR.getRandom(0,10,10))

and it would give something like this: [2, 2, 1, 4, 8, 1, 0, 7, 4, 5] But if I call the function again, it would append the new generatated numbers to the same list. So it would like something like this: [2, 2, 1, 4, 8, 1, 0, 7, 4, 5, 4, 5, 3, 1, 8, 6, 7, 5, 4, 4]

How do I get around this? How can I prevent fresh data to be appended to same list over and over again, which makes the list useless?

Thanks in advance!

Upvotes: 0

Views: 326

Answers (3)

jrasm91
jrasm91

Reputation: 428

Or even simplier would be the following

import random

def getRandom(start, end, quantity):
    return [random.choice(range(start, end)) for _ in range(quantity)]

print getRandom(0, 10, 10)

Upvotes: 0

Smita K
Smita K

Reputation: 94

import random
import math

resList=[]

class randomInRange:
    def getRandom(self, start, end, quantity):
        for i in range(quantity):
            selList = range(start, end)
            resNum = random.choice(selList)
        if resNum not in resList:
                resList.append(resNum) 

        return (resList)

RR=randomInRange()
print RR.getRandom(0,10,10)

Upvotes: 0

TerryA
TerryA

Reputation: 60004

That's because resList is a global variable and you never wipe its contents when calling randomInRange. You should just create the list in the function:

class randomInRange:
    def getRandom(self, start, end, quantity):
        resList = []
        for i in range(quantity):
            selList = range(start, end)
            resNum = random.choice(selList)
            resList.append(resNum)
        return (resList)

Note that your function can be replaced with a list comprehension too:

def getRandom(self, start, end, quantity):
    temp = range(start, end)
    return [random.choice(temp) for _ in range(quantity)]

Upvotes: 2

Related Questions