Iterating different portion of a list with different step size

suggest change

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:

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

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]:
    print(s)

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

The above snippet outputs:

bravo
delta

Indexing and slicing is a topic of its own.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Loops:
* Loops
* Iterating different portion of a list with different step size

Table Of Contents
2 Filter
3 List
7 Loops
22 Reduce
27 Classes
31 Set
42 Tuple
45 Enum
62 Sockets
89 urllib
92 Idioms
104 Stack
105 Profiling
109 Logging
111 os module
118 Mixins
120 ArcPy
126 Arrays
132 2to3 tool
135 Unicode
138 Neo4j
140 Curses
141 Templates
145 heapq
146 tkinter
154 Audio
155 pyglet
157 ijson
160 Flask
161 Groupby
163 pygame
165 hashlib
166 Gzip
167 ctypes
185 pyaudio
186 shelve