0

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?

1
  • since indexing starts with 0 the last item of a list is l[len(l) -1] or just l[-1] Commented Oct 28, 2021 at 6:58

4 Answers 4

3

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)
Sign up to request clarification or add additional context in comments.

1 Comment

@369 This is the correct answer! No need to know the length of the list at all, though you may want to check it's non-empty!
2

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)

Comments

1

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)

Comments

1

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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.