2

I'm randomly creating a list of tuples from two tuples, like so:

tuple1 = ('green','yellow','blue','orange','indigo','violet')
tuple2 = ('tree',2,'horse',4,6,1,'banana')

mylist = [(t1,t2) for item1 in tuple1 for item2 in tuple2]

which of course gives me something like:

[('green','tree'),('yellow', 2)] and so on.

But then, I want to randomly select one two-item tuple from the generated mylist. In other words, return something like ('green',2).

How do I randomly select one two-item tuple from a list of them? I tried the following, but it isn't working:

my_single_tuple = random.choice(mylist.pop())

I'd be grateful for any clues or suggestions.

[EDIT] I wasn't clear about the goal: I want to remove (pop) the randomly selected tuple from the list.

James
  • 1,568
  • 1
  • 15
  • 25

3 Answers3

4

If you want to select a tuple and then remove it just get the index and remove it afterwards.

import random

tuple1 = ('green','yellow','blue','orange','indigo','violet')
tuple2 = ('tree',2,'horse',4,6,1,'banana')

mylist = [(item1,item2) for item1 in tuple1 for item2 in tuple2]


while len(mylist) > 0:
    index = random.randint(0,len(mylist)-1)
    print(mylist[index])
    del mylist[index]
Philipp Braun
  • 1,583
  • 2
  • 25
  • 41
  • 2
    I said, *"that's why there's literally a `random.randrange`"*. I'm not sure what that last change was in aid of either, was there some problem with `list.pop`? Some indication that the OP wanted to clear out the list entirely and only ever print the elements in it? – jonrsharpe Dec 10 '16 at 22:50
  • 1
    Why not use random.shuffle *once* then just pop elements from the end? – Martijn Pieters Dec 11 '16 at 00:07
2

If you need to do this multiple times, just shuffle the list once and then pop items from the front:

random.shuffle(mylist)
mylist.pop()
mylist.pop()

etc.

RemcoGerlich
  • 30,470
  • 6
  • 61
  • 79
2

I think I found an answer that works:

my_item = mylist.pop(random.randrange(len(mylist)))

This successfully gives me a random tuple from the list. Thanks @philipp-braun, your answer was very close, but didn't work for me.

James
  • 1,568
  • 1
  • 15
  • 25