list loop get previous element 1

list loop get previous element

a_list = [1,2,3,4,5]

for index, elem in enumerate(a_list):
    if (index+1 < len(a_list) and index - 1 >= 0):
Check index bounds

        prev_el = str(a_list[index-1])
        curr_el = str(elem)
        next_el = str(a_list[index+1])

        print(prev_el, curr_el, next_el)

Here is what the above code is Doing:
1. We’re iterating over the list using enumerate()
2. We’re checking if the index is within bounds
3. We’re getting the previous, current and next elements
4. We’re printing them out

Similar Posts