Python - "random" error
Question: I am writing a code in Python 3.3.3 that makes a list of 32 teams if you enter
say 12 and makes sure that the team that is repeated the most is only repeated
once more than that which is being repeated the least. If have done this:

    
    
        import random
        teams =[]
        randoms = []
        team = 0
        amount = 1
        while team != "done":
            team = input("Please enter team name " + str(amount) +" or enter 'done' if you have finished.\n")
            if team != "done":
                teams.append(team)
                randoms.append(team)
                amount = amount + 1
        length = len(teams)
        times =0
        while len(teams) != 32:
            while len(teams) <= 32-length:
                for x in range (0,length+1):
                    teamname = teams[x]
                    teams.append(teamname)
            else:
               choice = random.choice(randoms)
               teams.append(choice)
               randoms.remove(choice)
            teams.sort()
        for x in range(0,len(teams)):
            print (teams[x])
    

I run the program and enter 12 teams then done. It comes up with the following
message:

    
    
    Traceback (most recent call last):
      File "C:\Python33\lib\random.py", line 248, in choice
        i = self._randbelow(len(seq))
      File "C:\Python33\lib\random.py", line 224, in _randbelow
        r = getrandbits(k)          # 0 <= r < 2**k
    ValueError: number of bits must be greater than zero
    
    
    During handling of the above exception, another exception occurred:
    
    
    Traceback (most recent call last):
      File "[File location]", line 30, in <module>
        choice = random.choice(randoms)
      File "C:\Python33\lib\random.", line 250, in choice
        raise IndexError('Cannot choose from an empty sequence')
    IndexError: Cannot choose from an empty sequence
    

What does this mean and how do I fix this?


Answer: That error occurs when the array in the random.choice() function is empty. I
suggest you use a Python Debugger to figure out when the array is completely
empty. It may help you to add a line of code to print len(teams) every loop to
see where your coding is messing up. It may be as simple as > versus >=.

Hope this helps!

