As I asked, is there a method or easy way to access the next and previous value from a list in a for?
JavaScript
x
5
1
for foo in reversed(values):
2
print(foo)
3
print(foo) # NEXT ONE
4
print(foo) # PREVIOUS ONE
5
Advertisement
Answer
List does not have methods to retrieve previous and/or next value of a list item. However, you can write some code to achieve this.
Let’s say you have a list of top five imaginary warriors:
warriors = ['Sam', 'Preso', 'Misus', 'Oreo', 'Zak']
and you want to find the previous and next warrior for each of the warrior in the list.
You can write some code (Note: You need Python >= 3.6)
Code
JavaScript
1
7
1
warriors = ['Sam', 'Preso', 'Misus', 'Oreo', 'Zak']
2
3
for i, warrior in enumerate(warriors):
4
print(f'Current: {warrior}')
5
print(f'Previous: {warriors[i-1] if i>0 else ""}')
6
print(f'Next: {warriors[i+1] if i<len(warriors)-1 else ""}')
7
Output