Using enumerate() to generate both offsets and items

Let’s suppose that we write a program and at a moment we need an item to use and an offset at the same time.

You can do it easily with a simple for loop that also keeps a counter of the current offset.

S1 = 'developer'
offset = 0
for i in S1:
	print(i, 'at offset no --> ', offset)
	offset += 1

The terminal output will be:

ddn_ro@Linux:~$ python3
d at offset no -->  0
e at offset no -->  1
v at offset no -->  2
e at offset no -->  3
l at offset no -->  4
o at offset no -->  5
p at offset no -->  6
e at offset no -->  7
r at offset no -->  8

An easier way of achieving the same result is to use the built-in enumerate(). It gives loops a counter automatically.

S1 = 'developer'

for (offset, i) in enumerate(S1):
	print(i, 'at offset no --> ', offset)

Leave a Reply