0

I am trying to add proxies randomly from a list to my browsers. I am trying to get each proxy randomly from the list but I keep getting duplicates being used. I have this code for the random proxy but I cannot seem to figure out how to make it not repeat.

random.shuffle(add_proxy)
for numb in range(0, num_tasks):
    proxy_addressed = add_proxy[numb]

this now uses only the correct amount of tasks for each proxy, what im stuck wondering is how can i make it do it again? After all the proxies are used, say i am using only 10 proxies but i make 15 'tasks', instead of getting the error list index is out of range, i want to reshuffle it and then assign any remaining tasks a proxy from the new shuffled list.

  • 2
    Maybe [random.sample](https://docs.python.org/3.5/library/random.html#random.sample) is what you are looking for? – Andrej Kesely Jan 04 '20 at 23:48
  • Can you share more of your code? – AMC Jan 05 '20 at 03:28
  • 1
    Does this answer your question? [Shuffling a list of objects](https://stackoverflow.com/questions/976882/shuffling-a-list-of-objects) – AMC Jan 05 '20 at 03:29

1 Answers1

3

You could just shuffle the list and then select from it sequentially:

import random

add_proxy = ['10.0.0.1', '10.0.0.2', '10.0.0.3', '10.0.0.4', '10.0.0.5']
random.shuffle(add_proxy)
num_tasks = 3
for numb in range(0, num_tasks):
    print(add_proxy[numb])

Sample output

10.0.0.3
10.0.0.1
10.0.0.4

If you have more tasks than proxies, you need to take the modulo of the task number with the length of the proxies array. If desired, you can shuffle the list each time they are all used:

add_proxy = ['10.0.0.1', '10.0.0.2', '10.0.0.3', '10.0.0.4', '10.0.0.5']
num_proxies = len(add_proxy)
num_tasks = 9
for numb in range(0, num_tasks):
    if numb % num_proxies == 0:
        random.shuffle(add_proxy)
    print(add_proxy[numb % num_proxies])

Sample output:

10.0.0.3
10.0.0.4
10.0.0.2
10.0.0.5
10.0.0.1
10.0.0.3
10.0.0.1
10.0.0.4
10.0.0.2
Nick
  • 138,499
  • 22
  • 57
  • 95
  • this works, now the issue i face is say i have only 8 proxies, i would in my code right now only be able to make 8 browsers bc i get the error list is out of range. How could i say that once they are all used, shuffle it again and then do the same? I will edit my code to show what i fixed. –  Jan 05 '20 at 04:34
  • 1
    @mferraro I've edited my answer with code to deal with that situation. – Nick Jan 05 '20 at 06:08