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

Georgia Fernández :

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
Saimon :

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

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=387125&siteId=1