Skip to content
Advertisement

Is there a list method in Python to access the next and/or previous value of a list item?

As I asked, is there a method or easy way to access the next and previous value from a list in a for?

for foo in reversed(values):
    print(foo)
    print(foo) # NEXT ONE
    print(foo) # PREVIOUS ONE

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

warriors = ['Sam', 'Preso', 'Misus', 'Oreo', 'Zak']

for i, warrior in enumerate(warriors):
  print(f'Current: {warrior}')
  print(f'Previous: {warriors[i-1] if i>0 else ""}')
  print(f'Next: {warriors[i+1] if i<len(warriors)-1 else ""}')

Output

enter image description here

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement