Python – Itertools.count()
Python Itertools are a great way of creating complex iterators which helps in getting faster execution time and writing memory-efficient code.
Itertools provide us with functions for creating infinite sequences and
itertools.count() is one such function and it does exactly what it sounds like, it counts!
Note: For more information, refer to Python Itertools
itertools.count() are generally used with
map() to generate consecutive data points which is useful in when working with data. It can also be used with
zip to add sequences by passing count as parameter.
Syntax: itertools.count(start=0, step=1)
start: Start of the sequence (defaults to 0)
step: Difference between consecutive numbers (defaults to 1)
Returns: Returns a count object whose .__next__() method returns consecutive values.
Let us get a deep understanding of this mighty sword using some simple Python programs.
Example #1: Creating evenly spaced list of numbers
itertools.count() can be used to generate infinite recursive sequences easily. Lets have a look
Even list: [0, 2, 4, 6, 8] Odd list: [1, 3, 5, 7, 9]
In the same way, we can also generate a sequence of negative and floating-point numbers. For better accuracy of floating-point numbers use
(start + step * i for i in count()).
Example #2: Emulating
As mentioned earlier,
count() can be used with
zip(). Let’s see how can we use it to mimic the functionality of
enumerate() without even knowing the length of list beforehand!
(1, 'Geeks') (2, 'for') (3, 'Geeks')
Note: Extra care must be taken while using
itertools.count() as it is easy to get stuck in an infinite loop.
The following code functions the same as
while True: thus proper termination condition must be specified.
for i in count(start=0, step=2): print(i)
Please Login to comment...