from a list of names, create a secret santa drawing thing in python

Here is a simple Python code snippet that randomly assigns the givers and receivers for a secret Santa gift exchange.

main.py
import random

names = ["Alice", "Bob", "Charlie", "Dave"]
receivers = names.copy()
random.shuffle(receivers)

for i, name in enumerate(names):
    receiver = receivers[(i+1)%len(names)]
    print(name, "gives a gift to", receiver)
232 chars
10 lines

Explanation of the code:

  • import random: to use the shuffle() method to randomly shuffle the list of names
  • names = ["Alice", "Bob", "Charlie", "Dave"]: the list of participants in the gift exchange
  • receivers = names.copy(): create a copy of the list names for the receivers
  • random.shuffle(receivers): shuffle the list of receivers randomly
  • for i, name in enumerate(names):: loop through the list of names using enumerate() to get the index and the name at each position
  • receiver = receivers[(i+1)%len(names)]: use modular arithmetic to assign the next person in the list of receivers. %len(names) ensures that we wrap around to the beginning of the list.
  • print(name, "gives a gift to", receiver): print the giver and receiver of the gift.

Note: This code assumes that there are no duplicates in the list of names. If there are duplicates, you can either remove them before running the code or modify the code to handle duplicates.

gistlibby LogSnag