4

SO, I am searching for a way to loop through a list of items in a for loop fashion, except I want the loop to iterate in a 'random' way. i.e. I dont want the loop to go 0,1,2,3,m+1...n, I want it to pick it in some random order and still run through the loop for all items.

Here is my current looping code:

for singleSelectedItem in listOfItems:
  item = singleSelectedItem.databaseitem
  logging.info(str(item))    

please let me know if this doesnt make sense ;)

oberbaum
  • 2,451
  • 7
  • 36
  • 52

4 Answers4

9

If listOfItems can be shuffled, then

import random
random.shuffle(listOfItems)
for singleSelectedItem in listOfItems:
    blahblah

otherwise

import random
randomRange = range(len(listOfItems))
random.shuffle(randomRange)
for i in randomRange:
    singleSelectedItem = listOfItems[i]
    blahblah

Edit for Jochen Ritzel's better approach in the comment.
The otherwise part can be

import random
for item in random.sample(listOfItems, len(listOfItems))
    blahblah
clyfish
  • 10,240
  • 2
  • 31
  • 23
1
import random
random.shuffle(listOfItems)

for singleSelectedItem in listOfItems:
  item = singleSelectedItem.databaseitem
  logging.info(str(item))
phihag
  • 278,196
  • 72
  • 453
  • 469
1

Well if performance isn't that important you could just shuffle your items, or if those have to stay in the same order create a list of all indizes and shuffle that (eg indizes = range(len(listOfItems)), random.shuffle(indizes))

Voo
  • 29,040
  • 11
  • 82
  • 156
0
>>> lst = ['a', 'b', 'c', 'd']
>>> nums = list(range(0, len(lst)))
>>> import random
>>> random.shuffle(nums)
>>> for i in nums:
...     print lst[i]
c
a
b
d

Or if the list is really large you can use a bit of generator flavoring. :-)

Sanjay T. Sharma
  • 22,857
  • 4
  • 59
  • 71