2

Here is my conundrum.Imagine you have a loop and a list with 100 members in python like the following:

myList=range(100)

for i in range(100):
    print(myList[i]) 
    print(myList[i+5])
    print(myList[i-5])

How would one prevent the index of myList from exceeding the length of the list or going under 0?

For example, if the index in the loop was 99 then:

print(myList[i+5])

would return an index error.

To clarify, I mean so that I could find out what [i+5] as if the list was on a loop.

So if you imagine that the index was 99 (again) I would like to go to the 4th index (after adding 5 and looping back to the start).

2
  • Start from 5 and end before the length - 5? Commented Apr 2, 2014 at 15:38
  • I should have made this clearer.I am using this for a game which loops the last pixel with the start pixel so I want to be able to move the index past the end of the list and start at the start again. Commented Apr 2, 2014 at 15:45

2 Answers 2

2

The straight forward way would be to start from 5 and end at the length of the list - 5, like this

for i in range(5, len(myList) - 5):
    print(myList[i]) 
    print(myList[i+5])
    print(myList[i-5])

Or you can make sure that the index is valid before accessing the element at that location, like this

for i in range(100):
    print(myList[i])
    if i + 5 < len(myList):
        print(myList[i+5])
    if i - 5 >= 0:
        print(myList[i-5])

Edit: If you like to wrap around and start from the other end, once you reached an end, then you can use modulo operator, like this

for i in range(100):
    print(myList[i])
    print(myList[(i + 5) % len(myList)])
    print(myList[(i - 5) % len(myList)])
Sign up to request clarification or add additional context in comments.

Comments

1

You could also define a "safe" print function:

EDIT: After your clarification, I modified my answer to be circular

def safe_print(mylist, myindex):
    print mylist[myindex % len(mylist)]

myList=range(100)

for i in range(100):
    safe_print(myList, i)
    safe_print(myList, i+5)
    safe_print(myList, i-5)

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.