Thanks to visit codestin.com
Credit goes to www.tutorialspoint.com

Selected Reading

Python itertools.count() Function



The Python itertools.count() function is used to create an iterator that generates an infinite sequence of numbers, starting from a specified value and incrementing by a given step. This function is commonly used for generating counters in loops or for creating sequences of numbers dynamically.

By default, the function starts from 0 and increments by 1 if no arguments are provided.

Syntax

Following is the syntax of the Python itertools.count() function −

itertools.count(start=0, step=1)

Parameters

This function accepts the following parameters −

  • start (optional): The starting value of the sequence (default is 0).
  • step (optional): The difference between consecutive values (default is 1).

Return Value

This function returns an iterator that produces an infinite sequence of numbers.

Example 1

Following is an example of the Python itertools.count() function. Here, we are generating an infinite sequence of numbers starting from 5 −

import itertools

counter = itertools.count(5)
for _ in range(5):
   print(next(counter))

Following is the output of the above code −

5
6
7
8
9

Example 2

Here, we specify a step value of 2, generating an arithmetic sequence with a difference of 2 between each value −

import itertools

counter = itertools.count(10, 2)
for _ in range(5):
   print(next(counter))

Output of the above code is as follows −

10
12
14
16
18

Example 3

Now, we use the itertools.count() function with a floating-point step value to generate a sequence of decimal numbers −

import itertools

counter = itertools.count(1.5, 0.5)
for _ in range(5):
   print(next(counter))

The result obtained is as shown below −

1.5
2.0
2.5
3.0
3.5

Example 4

If you use the itertools.count() function without limiting its iteration, it will run indefinitely. To prevent infinite loops, you can use conditions or the islice() function from itertools.

Here, we generate a sequence of numbers but limit it using itertools.islice() function −

import itertools

counter = itertools.count(0, 3)
limited_counter = itertools.islice(counter, 5)
for num in limited_counter:
   print(num)

The result produced is as follows −

0
3
6
9
12
python_modules.htm
Advertisements