1

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
  • 407
  • 2
  • 11
  • Use a while loop. – Sayse Mar 30 '20 at 10:15
  • See https://stackoverflow.com/q/6822725/3001761 – jonrsharpe Mar 30 '20 at 10:16
  • Does this answer your question? [Rolling or sliding window iterator?](https://stackoverflow.com/questions/6822725/rolling-or-sliding-window-iterator) – Tomerikoo Mar 30 '20 at 10:18
  • 1
    There are various approaches possible… you could create a `zip(r_values, r_values[1:])` to iterate over two offset values at once (or more if you need). Alternatively `enumerate(r_values)` to also get the index, and access other indices from the list. – deceze Mar 30 '20 at 10:19
  • @deceze Hey there, I'd like to do the subtraction between foo[n] and foo[n-1], for the whole values for the list. How could I do that with zip? – Georgia Fernández Mar 30 '20 at 10:29

1 Answers1

2

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

Saimon
  • 407
  • 2
  • 11
  • Thanks for your answer, @deceze talked about using zip for this one as well, I wonder if would you be so kind as to show me an example with zip? – Georgia Fernández Mar 30 '20 at 10:51
  • 1
    I am not sure how to achieve the same result with the same list using zip, as @deceze mentioned in a comment. However, if you are satisfied with the answer I provided, you can accept it. Thanks. – Saimon Mar 30 '20 at 12:31