Suppose you have a long list of elements and you are only interested in every other element of the list. Perhaps you only want to examine the first or last elements, or a specific range of entries in your list. Python has strong indexing built-in capabilities. Here are some examples of how to achieve these scenarios.
Here's a simple list that will be used throughout the examples:
lst = ['alpha', 'bravo', 'charlie', 'delta', 'echo']
To iterate over each element in the list, a
for loop like below can be used:
for s in lst: print s[:1] # print the first letter
for loop assigns s for each element of
lst. This will print:
a b c d e
Often you need both the element and the index of that element. The
enumerate keyword performs that task.
for idx, s in enumerate(lst): print("%s has an index of %d" % (s, idx))
idx will start with zero and increment for each iteration, while the
s will contain the element being processed. The previous snippet will output:
alpha has an index of 0 bravo has an index of 1 charlie has an index of 2 delta has an index of 3 echo has an index of 4
If we want to iterate over a range (remembering that Python uses zero-based indexing), use the
for i in range(2,4): print("lst at %d contains %s" % (i, lst[i]))
This would output:
lst at 2 contains charlie lst at 3 contains delta
The list may also be sliced. The following slice notation goes from element at index 1 to the end with a step of 2. The two
for loops give the same result.
for s in lst[1::2]: print(s) for i in range(1, len(lst), 2): print(lst[i])
The above snippet outputs:
Indexing and slicing is a topic of its own.