7. itertools.repeat(), itertools.cycle(), itertools.count(): Make Infinite Iterables

Sumit Rawal answered on May 13, 2023 Popularity 1/10 Helpfulness 1/10

Contents


More Related Answers


7. itertools.repeat(), itertools.cycle(), itertools.count(): Make Infinite Iterables

0

In some cases, we need to get an infinite iterable. There are 3 functions that are helpful:

itertools.repeat(): Generate the same item repeatedly

For example, we can get three same “Yang” as follows:

import itertools

print(list(itertools.repeat('Yang', 3)))

# ['Yang', 'Yang', 'Yang']

itertools.cycle(): Get an infinite iterator by cycling

The itertools.cycle function will not stop until you break the loop:

import itertools

count = 0

for c in itertools.cycle('Yang'):

if count >= 12:

break

else:

print(c, end=',')

count += 1

# Y,a,n,g,Y,a,n,g,Y,a,n,g,

itertools.count(): generate an infinite sequence of numbers

If all we need is numbers, use the itertools.count function:

import itertools

for i in itertools.count(0, 2):

if i == 20:

break

else:

print(i, end=" ")

# 0 2 4 6 8 10 12 14 16 18

As illustrated above, its first parameter is the starting number, and the second parameter is the step. 

Popularity 1/10 Helpfulness 1/10 Language whatever
Source: Grepper
Link to this answer
Share Copy Link
Contributed on May 13 2023
Sumit Rawal
0 Answers  Avg Quality 2/10


X

Continue with Google

By continuing, I agree that I have read and agree to Greppers's Terms of Service and Privacy Policy.
X
Grepper Account Login Required

Oops, You will need to install Grepper and log-in to perform this action.