The code runs just fine for a while before resulting in an index error. This is the error message I keep getting This is the code:
import random
import time
Male_First_Names = ['Albert', 'Arnold', 'Alexander', 'Andrew', 'Bernard', 'Bertrand', 'Charles', 'Christopher', 'Conall', 'Craig', 'Derrick', 'Donald', 'Dwight','Douglas', 'Erwin', 'Edward', 'Elmer', 'Ernest', 'Frederick', 'Gerald', 'Garfield', 'Godfrey', 'George', 'Henry', 'Hubert', 'Howard', 'Herman', 'Jonathan', 'James', 'Jack', 'Kevin', 'Karl', 'Kenneth', 'Keith', 'Lawrence', 'Ludwig', 'Lloyd', 'Mark', 'Nicholas', 'Oscar', 'Oswald', 'Paul', 'Philip', 'Richard', 'Ralph', 'Scott', 'William', 'Wilbur', 'Walter']
Last_Names = ['Clark', 'Smith', 'Thompson', 'Lewis', 'Martin', 'Wright', 'Hughes', 'Stewart', 'Campbell', 'Adams']
x = True
while x == True:
y = len(Male_First_Names)
y1 = y-1
z = len(Last_Names)
z1 = z-1
r = Male_First_Names[random.randint(0, y1)]
Male_First_Names.remove(r)
print(r+' ' + Male_First_Names[random.randint(0, y1)]+' '+ Last_Names[random.randint(0, z1)])
Male_First_Names.insert(len(Male_First_Names),r)
time.sleep(0.25)
I wrote a name generator which generators names with a first name, last name, and middle name. It has 2 lists, one with first names, and the other with last names. The code basically picks an element (name) from the first names list at random and uses it as the first name. Then it temporarily removes that name from the list and picks another name from the first names list and uses that name as the middle name. Then it picks an element from the last names list at random and uses it as the last name. Lastly, it inserts the first name that was picked and inserts it back into the first names list and repeats the process. The problem is that while the code runs just fine for a while, an index error eventually occurs. I know that index errors occur when trying to access an element using an index that is outside the valid range of indices for that particular sequence; however, I don't see why that error keeps occurring. What is the problem and how do I fix it?
You modify the list of first names but don't change
y1- the last valid index. so when you do:You always run the rick of the middle name going off the end of the list.
Would be one way to fix it, but I'd probably use a new variable to make it clearer what is going on - it's already hard to read.