# Input list.
elements = [0, 10, 20, 30]
# Use range.for i in range(1, len(elements)):
# Get two adjacent elements.
a = elements[i - 1]
b = elements[i]
# Print 2 elements.
Enumerate list. Here we use the enumerate method to loop over a list. We unpack a tuple of (index, element) at each iteration of the loop.
colors = ["green", "orange", "yellow"]
# Call enumerate() to access indexes and elements.# ... Unpack each tuple returned from enumerate().
for i, color in enumerate(colors):
Reverse indexes. Suppose we want to loop over a list in reverse, from the last to the first index. We can use a range() call and specify a step of -1, which means "go backwards."
Important The range() call here does not return the indexes, but returns 1 greater than the indexes, so we must subtract 1.
ids = [201, 202, 203]
# Loop over the list indexes in reverse order (from last to first).# ... We go from the length and stop after 1.# So we must subtract 1 to get the indexes.for i in range(len(ids), 0, -1):
print("INDEX:", i - 1)
print("ID:", ids[i - 1])
Reversed list, for. Sometimes we do not need the indexes of each element—we just want the elements themselves. Here we call reversed() to act upon a reversed view of the list.
And We then use a for-loop over the reversed view of the list. We print the element values to the console.
ids = [600, 601, 602]
# Loop over list in reverse.
for id in reversed(ids):
A summary. Lists are made to be looped over—looping is a fast and natural operation on Python lists. We can loop over indexes, or the elements themselves.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on 8/12/2022 (edit link).