Junior — Middle
How can a mechanism be implemented to sequentially obtain random or pre-defined values?
sobes.tech AI
Answer from AI
To sequentially obtain random or predefined values in Python, you can use generators or iterators.
Example with predefined values:
def predefined_sequence():
values = [10, 20, 30, 40]
for v in values:
yield v
seq = predefined_sequence()
print(next(seq)) # 10
print(next(seq)) # 20
Example with sequential random values:
import random
def random_sequence(n):
for _ in range(n):
yield random.randint(1, 100)
rand_seq = random_sequence(5)
for val in rand_seq:
print(val)
Thus, generators allow for an easy implementation of a mechanism to sequentially obtain values without the need to store the entire sequence in memory.