Python Language Loops Iterating different portion of a list with different step size

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!


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']

Iteration over the whole list

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

The for loop assigns s for each element of lst. This will print:


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))

The index 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

Iterate over sub-list

If we want to iterate over a range (remembering that Python uses zero-based indexing), use the range keyword.

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]:

for i in range(1, len(lst), 2):

The above snippet outputs:


Indexing and slicing is a topic of its own.

Got any Python Language Question?