enumerate()

Introduction

In this article you will learn how the function enumerate() works in Python 3.

enumerate() takes an iterable and returns a set of tuples of the form (element index, element)

If you want to repeat the examples from the article, create a file enumerate_demo.py and copy the code from the examples into it.

You can run the file with the command

python3 enumerate_demo.py

Syntax

enumerate(iterable, start=0)

Official documentation

Return an enumerate object. iterable must be a sequence, an iterator, or some other object which supports iteration.

The __next__() method of the iterator returned by enumerate() returns a tuple containing a count (from start which defaults to 0) and the values obtained from iterating over iterable.

>>> seasons = ['Spring', 'Summer', 'Fall', 'Winter'] >>> list(enumerate(seasons)) [(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')] >>> list(enumerate(seasons, start=1)) [(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]

Equivalent to:

def enumerate(iterable, start=0): n = start for elem in iterable: yield n, elem n += 1

Example

Let's walk through the function enumerate() over a list and at the same time make sure that it returns tuples (tuple)

sites = ["heihei.ru", "topbicycle.ru", "urn.su"] for site in enumerate(sites): print(f"site: {site}, type(site): {type(site)}")

site: (0, 'heihei.ru'), type(site): <class 'tuple'> site: (1, 'topbicycle.ru'), type(site): <class 'tuple'> site: (2, 'urn.su'), type(site): <class 'tuple'>

Details

Let's look at ways to iterate over the objects of a list

letters = ['a', 'b', 'c', 'd', 'e'] for letter in letters: print(letter)

python enumerate_demo.py

a b c d e

If you need to show not only the element but also its index, this is easy to do manually by adding a variable.

index = 0 letters = ['a', 'b', 'c', 'd', 'e'] for letter in letters:     print(index, letter)     index += 1

0 a 1 b 2 c 3 d 4 e

As an alternative, you can use range() or while in combination with len()

for index in range(len(letters)):     print('letters[', index, '] =', letters[index]) # or index = 0 while index < len(letters): print('letters[', index, '] =', letters[index]) index += 1

python enumerate_demo.py

letters[ 0 ] = a letters[ 1 ] = b letters[ 2 ] = c letters[ 3 ] = d letters[ 4 ] = e

To use two variables at the same time, the function enumerate()

for index, item in enumerate(letters): print('letters', index, '=', item)

python enumerate_demo.py

letters 0 = a letters 1 = b letters 2 = c letters 3 = d letters 4 = e

enumerate() returns an iterator (iterator) , in which you can iterate over a sequence of tuples (tuple) of the form (index, item)

To better understand what is happening, add the following code to the script

enum_obj = enumerate(letters) print(next(enum_obj)) print(next(enum_obj)) print(next(enum_obj)) print(type(enum_obj))

(0, 'a') (1, 'b') (2, 'c') <class 'enumerate'>

An example of using enumerate() together with glob to find and count files.

Deleting lines by number

To better understand this example, you need to master the material of the article «Basics of working with files in Python»

If you need to delete a certain range of lines from some file, enumarate() will come in very handy.

Let's look at the file sample.txt

cat sample.txt

First line Second line Third line Fourth line Fifth line Sixth line Seventh line Eighth line

To delete lines 4 and 7 we will use the script

# list to store file lines lines = [] path = "sample.txt" # Read file with open(path, 'r') as f: # read an store all lines into list lines = f.readlines() # Write file with open(path, 'w') as f: # iterate each line for number, line in enumerate(lines): # delete line 5 and 8. or pass any Nth line you want to remove # note list index starts from 0 if number not in [4, 7]: f.write(line)

python delete.lines.py
cat sample.txt

First line Second line Third line Fourth line Sixth line Seventh line

Article author: Andrei Olegovich