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 ;)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With