Skip to content
Advertisement

How can I use Yield and Range to get the position and item from a list?

I’d like to implement yield and range to challenge myself and get a better understanding of both. I’m trying to use yield to loop through a function to get a random number within the list. And range used somewhere within as well. The current function below I have isn’t currently working.

NumList = [6,9,32,39,61,75,60,63,22,49,26,4,64,54,78,43,1,47,46,17,69,20,85,71,93,28,89,67,14,88,15,73,96,86,55,79,68,76,94,65]

def PenTune(): 
    for NumList in range(1):
        yield random.choice(list(enumerate(NumList)))

for pos, item in PenTune():
       print("pos:", pos, "itemvalue:", item)

Advertisement

Answer

The following may hint you at what’s going on:

numList = [6,9,32,39,61,75,60,63,22,49,26,4,64,54,78,43,1,47,46,17,69,20,85,71,93,28,89,67,14,88,15,73,96,86,55,79,68,76,94,65]

def PenTune(): 
    e = list(enumerate(numList))  # only listify it once
    for _ in range(5):  # or how many random index-value pairs you want
        yield random.choice(e)

for pos, item in PenTune():
    print("pos:", pos, "itemvalue:", item)

pos: 37 itemvalue: 76
pos: 16 itemvalue: 1
pos: 29 itemvalue: 88
pos: 32 itemvalue: 96
pos: 8 itemvalue: 22

A less wasteful implementation:

def PenTune(): 
    for _ in range(5):
        i = random.randint(0, len(numList)-1)
        yield i, numList[i]
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement