9
list1 = [1,2,3,4] 

If I have list1 as shown above, the index of the last value is 3, but is there a way that if I say list1[4], it would become list1[0]?

2
  • 2
    Try list[-1]. Commented Mar 2, 2018 at 2:12
  • 3
    Nevermind, I can't read. Commented Mar 2, 2018 at 2:13

3 Answers 3

9

You can you modulo math like:

Code:

list1 = [1, 2, 3, 4] print(list1[4 % len(list1)]) 

Results:

1 
Sign up to request clarification or add additional context in comments.

Comments

3

In the situation you described, I myself use the method @StephenRauch suggested. But given that you added cycle as a tag, you might want to know there exists such a thing as itertools.cycle.

It returns an iterator for you to loop forever over an iterable in a cyclic manner. I don't know your original problem, but you might find it useful.

import itertools for i in itertools.cycle([1, 2, 3]): # Do something # 1, 2, 3, 1, 2, 3, 1, 2, 3, ... 

Be careful with the exit conditions though, you might find yourself in an endless loop.

Comments

3

You could implement your own class that does this.

class CyclicList(list): def __getitem__(self, index): index = index % len(self) if isinstance(index, int) else index return super().__getitem__(index) cyclic_list = CyclicList([1, 2, 3, 4]) cyclic_list[4] # 1 

In particular this will preserve all other behaviours of list such as slicing.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.