Reputation: 53
list = ['john','james','michael','david','william']
winner = []
How can I remove a random item from list
and add it to winner
?
Upvotes: 1
Views: 2550
Reputation: 2963
winner.append(list.pop(random.randrange(0,len(list))))
To break this down:
random.randrange(0,len(list))
will generate a random number between zero and the length of your list inclusive. This will generate a random index in your list that you can reference.
list.pop(i)
This will remove the item at the specified index (i) from your list.
winner.append(x)
This will add an item (x) to the end of the winner list. If you want to add the item at a specific index, you can use
winner.insert(i,x)
with i being the index to insert at and x being the value to insert.
If you want more information, a good reference is the python docs on data structures: https://docs.python.org/2/tutorial/datastructures.html
Upvotes: 4
Reputation: 339220
This selects a random item from a list of names names
and adds it to another list winner
. The chosen winner is then removed from the names
.
import random
winner = []
names = ['john','james','michael','david','william']
winnerindex = random.randint(0,len(names)-1)
winner.append(names[winnerindex])
del names[winnerindex]
print winner, names
Upvotes: 0
Reputation: 83
Simply use random.randint from index 0 to len(list) to get the index of the element of list and append it to winner.
import random
index = random.randomint(0, len(list)-1)
winner.append(list[index])
del list[index]
Upvotes: -2