You could use the modulo operator!
i = len(l) - 1
jIndex = (i - 1) % len(l)
kIndex = (i + 1) % len(l)
j = l[jIndex]
k = l[kIndex]
Or, to be less verbose:
k = l[(i + 1) % len(l)]
More Related Contents:
- What does += mean in this context?
- Most efficient way to build single-element list from string with or without spaces? [closed]
- How to name a file using a value in a list in a dictionary?
- What does “list comprehension” and similar mean? How does it work and how can I use it?
- Why does append() always return None in Python? [duplicate]
- How to group dataframe rows into list in pandas groupby
- Convert all strings in a list to int
- Get unique values from a list in python [duplicate]
- Element-wise addition of 2 lists?
- Sum a list of numbers in Python
- List comprehension vs generator expression’s weird timeit results?
- Python copy a list of lists [duplicate]
- Calculating arithmetic mean (one type of average) in Python [duplicate]
- How do I loop through a list by twos? [duplicate]
- converting a list of integers into range in python
- Modifying a list while iterating over it – why not? [duplicate]
- How to make a set of lists
- How can I find same values in a list and group together a new list?
- How to create a list with the characters of a string? [duplicate]
- TypeError: ‘float’ object is not subscriptable
- Python .sort() not working as expected
- Fastest way to count number of occurrences in a Python list
- Python 3 range Vs Python 2 range
- Convert List to Pandas Dataframe Column
- Creating a dictionary with list of lists in Python
- Getting indices of True values in a boolean list
- Python: How to sort a list of dictionaries by several values?
- Reading specific columns from a text file in python
- How does str(list) work?
- Removing an item from a list of lists based on each of the lists first element