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?

JavaScript

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

Output

enter image description here

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