1

In my quest to solve a dictionary issue I had, I came across this simple function for generating random numbers.

import random
a = random.randint(1,10)
print('string_{}'.format(a))

This works great, but what I really needed is a function that does exactly that, but for consecutive numbers, i.e that goes 1,2,3,4,5...

I know of generators, iterators, while counters, using for loops, but I was looking for this kind of simple solution: something that will do the same action as the random function but for consecutive numbers.
Do you know if that option exists?

EDIT: Thanks for all of the responders, but I am trying to find an easy one liners
like this a = random.randint(1,10) but for consecutive numbers (i.e not random)

soBusted
  • 197
  • 3
  • 18
  • 3
    can you be a bit more specific – raven404 May 18 '20 at 09:06
  • 1
    Sounds like [count function](https://docs.python.org/2/library/itertools.html#itertools.count). `count(start=1, step=1)` produces a generator for 1,2,3,4,5,... – DarrylG May 18 '20 at 09:07
  • Does this answer your question? [Easy way to keep counting up infinitely](https://stackoverflow.com/questions/11424808/easy-way-to-keep-counting-up-infinitely) – Tomerikoo May 18 '20 at 10:50

2 Answers2

1

The user who suggested the count() function is correct. However, here is what that would look like, in case you want to make additional modifications.

import random

def getNextRandom(start, end):

    initial = random.randint(start, end)

    while True:
        yield initial
        initial = initial + 1

A = getNextRandom(0, 100)

print ("\nGetting the first 3 values")
rand1 = next(A)
rand2 = next(A)
rand3 = next(A)
print (rand1, rand2, rand3)

print ("\nIterating to get 5 more values")
for ii in range(5):
    print (next(A))

Output:

$ python rand.py

Getting the first 3 values
44 45 46

Iterating to get 5 more values
47
48
49
50
51
AndrewGrant
  • 786
  • 7
  • 17
0

Is this want you want?

lastNumber = 0

def nextNumber():
  global lastNumber
  lastNumber += 1
  return lastNumber

print(nextNumber())
print(nextNumber())
print(nextNumber())

Output:

1
2
3
Heath Mitchell
  • 372
  • 3
  • 13