Movatterモバイル変換


[0]ホーム

URL:


Python Tutorial

Python itertools.count() Function



The Pythonitertools.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 itertoolscounter = itertools.count(5)for _ in range(5):   print(next(counter))

Following is the output of the above code −

56789

Example 2

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

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

Output of the above code is as follows −

1012141618

Example 3

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

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

The result obtained is as shown below −

1.52.02.53.03.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 theislice() function from itertools.

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

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

The result produced is as follows −

036912
python_modules.htm
Print Page
Advertisements

[8]ページ先頭

©2009-2025 Movatter.jp