-1

I just learnt how to remove something from a list.

rando = keywords[random.randint(0, 14)]
h = 0
for h in range(len(keywords)):
    if rando == keywords[h]:
        position = h

realAns = definitions[position]
del keywords [h]

However, as I am using a while loop, a part of the code keeps repeating, and as I have changed the range by deleting an element, a traceback error occurs saying that it is out of range. How do i fix this? Thanks :)

anon582847382
  • 19,907
  • 5
  • 54
  • 57

2 Answers2

0

The code looks fine, may be you have not defined the list 'keywords' with 14 entries in the list.

You get the 'list out of range' error when you are trying to access a part of list which is not defined. For example see following code

list_of_rollnumbers = [11,24,31,57,42,99,132]
print list_of_rollnumbers[7]
print list_of_rollnumbers[9] #both these would give list index out of range error
print list_of_rollnumbers[5] #this would print 99
Rookie Learner
  • 45
  • 1
  • 2
  • 8
0

Why are you even doing that loop? As I understand it, you pick the item at a random index, then look through the whole list to find the item so you can find its index. Just do:

position = random.randrange(len(keywords))
rando = keywords[position]
realAns = definitions[position]

Or, much simpler:

rando, realAns = random.choice(list(zip(keywords, definitions)))
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437