Peanutpower
Peanutpower

Reputation: 1

Python list assignment index out of range

I just can't understand why my list is out of range.

I've been stuck on this problem forever now and can't wrap my head around what the problem might be.

Obviously I'm new into programming.

def list(self,filename):
    with open(filename, "r") as listTeams:
        teamCount = 0
        indexList = []
        unsortedList = []
        lines = listTeams.readlines()

        for line in open(filename):
            teamCount += 1

        listTeams.seek(0)

        for i in range(0, teamCount):
            tempStr = listTeams.readlines(i)
            tempStr = "".join(tempStr)
            indexList = tempStr.split(" ")
            for i in range(0,i):
                print(i)
                unsortedList[i] = Team(indexList[0], indexList[1], indexList[2], indexList[3], indexList[4], indexList[5], indexList[6])
                print(unsortedList[i])
    return

I get this error message:

unsortedList[i] = Team(indexList[0], indexList[1], indexList[2], indexList[3], indexList[4], indexList[5], indexList[6])
IndexError: list index out of range

Upvotes: 0

Views: 3990

Answers (2)

Diksha Dhawan
Diksha Dhawan

Reputation: 327

You can't assign values to List items which don't exist. You can use one of the two methods to solve this problem. One, you can use this command unsortedList.append(Team(indexList[0], indexList[1], indexList[2]). or Second, you can create a list apriori which contains as many zeros as your list will contain by using the command unsortedList= numpy.zeros(i), it will create a list with i number of zeros then you can replace those zeros using your code.

Upvotes: 1

Damith
Damith

Reputation: 63065

you can't assign to a list element that doesn't already exist, you can use append method

unsortedList.append(Team(indexList[0], indexList[1], indexList[2], indexList[3], indexList[4], indexList[5], indexList[6]))

also check the how many items in the array before accessing by index len(indexList) give you the number of items in the array, check that is more than 6 before you get the items 0 to 6 in the indexList

Upvotes: 0

Related Questions