Home > OS >  Python, index out of range, list
Python, index out of range, list

Time:10-28

I need to change the number with the highest index and the number with the lowest index between each other in the entered line, but an error pops out

Error:

    list2[0], list2[len1] = list2[len1], list2[0]
IndexError: list index out of range

Code:

list1 = input("Введите список: ")
list2 = list1.split()
len1 = int(len(list2))
list2[0], list2[len1] = list2[len1], list2[0]
print(list2)

How can this be fixed?

CodePudding user response:

List are indexing from 0. If your list contains 4 elements, the length is 4 but the last index is 3 (4 - 1).

list1 = input("Введите список: ")
list2 = list1.split()
len1 = int(len(list2)) - 1  # <- HERE
list2[0], list2[len1] = list2[len1], list2[0]
print(list2)

CodePudding user response:

Use index [-1] instead of len(list2)-1 to get the last element:

list1 = input("Введите список: ").split()
list1[0], list1[-1] = list1[-1], list1[0]
print(list1)

CodePudding user response:

The indexing is always 0 - length-1.

So if you take the list value at length, it will be out of the aforementioned index range.

Another thing I would like to point out is that your variable names are really very confusing. It's a small code, however for bigger projects, when you'll have to debug this, it will be a serious pain for you.

However, this should work

ip = input("Введите список: ")
list1 = ip.split(" ")
len1 = int(len(list1))
list1[0], list1[len1-1] = list1[len1-1], list1[0]
print(list1)

CodePudding user response:

As the Error states, the index for the "list2[len1]" is out of range.

Since len() method in python returns the actual length of the list, whereas the indexing of list starts with 0th position

for the above code, you can try doing this:

list2[0], list2[len1-1] = list2[len1-1], list2[0]
  • Related