How to iterate a list from the middle outward (stepping left and right alternately) in Python

1 Answer

0 votes
# List to iterate
lst = [0, 1, 2, 3, 4, 5, 6, 7]
n = len(lst)

# Middle index for even-sized lists
mid = n // 2

# Left starts before the middle, right starts at the middle
left = mid - 1
right = mid

# Iterate outward from the middle
while left >= 0 or right < n:

    if right < n:
        print(lst[right], end=" ")
        right += 1

    if left >= 0:
        print(lst[left], end=" ")
        left -= 1


"""
run:

4 3 5 2 6 1 7 0 

"""

 



answered Jun 29 by avibootz

Related questions

...