Python Forum

Full Version: repeating for loop
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello guys,
Is there any command for repeating for cycle? I need to have done list of numbers that do not repeat...
z=[]
for i in range(15):
    number=random.randint(0,99)
    if number not in z:
        z.append(number)
...but in my code when two numbers are same I get only 14 numbers in list and throws error "list index out of range"

Thank you!
one way - don't use for loop. use while loop instead

z=[]
while len(z) < 15:
    number=random.randint(0,99)
    if number not in z:
        z.append(number)
If you want the numbers from 0 to n in random order without repeats, use shuffle:

numbers = list(range(n + 1))
random.shuffle(numbers)
I don't see how you could get an IndexError, since there are no list indexes in your code. If the above does not solve your problem, please post the full text of the error.
First, we start with a generator that produces an infinite stream of random numbers:
>>> import random
>>> def random_numbers(min_val, max_val):
...     while True:
...         yield random.randint(min_val, max_val)
...
Then, we write a function that takes a stream, and filters out duplicate values:
>>> def unique_values(sequence):
...     seen_before = set()
...     for item in sequence:
...         if item not in seen_before:
...             seen_before.add(item)
...             yield item
...
Then, we write another function which takes a stream of some kind, and takes only the first few items off of it:
>>> def take(num, sequence):
...     sequence = iter(sequence)
...     for _ in range(num):
...         yield next(sequence)
...
Putting all those together, we can generate any number of uniquely random numbers:
>>> list(take(5, unique_values(random_numbers(0, 7))))
[6, 5, 1, 0, 7]
@ichabood - I guess they have extra code. Also they want list with len 15.
@Kaldesyvon: to extend what ichabood suggests:
>>> import random
>>> nums = list(range(100))
>>> random.shuffle(nums)
>>> z = nums[:15]
>>> z
[15, 34, 29, 20, 24, 31, 86, 62, 41, 38, 11, 72, 60, 85, 13]
>>> 
(Dec-06-2018, 07:56 PM)buran Wrote: [ -> ]I guess they have extra code. Also they want list with len 15.

I was not clear to me what they wanted. I saw the 15 loop, but I wasn't sure if that was because they wanted 15 numbers or not.