Looping through variables in Python

Question:

I’ve written a program to randomly assign teams to four people for a World Cup sweepstakes. The code works fine, but it’s ugly. How do I shuffle the variables Seed1, Seed2, … Seed8 with a loop? How do I print which teams have been assigned to each player with more professional looking code?

import random

Teams = ["Alice", "Bob","Charlie", "Delilah"]

random.shuffle(Teams)

Seed1 = ["Brazil", "Argentina", "France", "Spain"]
Seed2 = ["England", "Germany", "Netherlands", "Portugal"]
Seed3 = ["Belgium", "Denmark", "Uruguay", "Croatia"]
Seed4 = ["Serbia", "Switzerland", "Senegal", "Mexico"]
Seed5 = ["USA", "Poland", "Ecuador", "Morocco"]
Seed6 = ["Wales", "Japan", "Ghana", "Canada"]
Seed7 = ["Qatar", "South Korea", "Iran", "Cameroon"]
Seed8 = ["Australia", "Saudi Arabia", "Tunisia", "Costa Rica"]

random.shuffle(Seed1)
random.shuffle(Seed2)
random.shuffle(Seed3)
random.shuffle(Seed4)
random.shuffle(Seed5)
random.shuffle(Seed6)
random.shuffle(Seed7)
random.shuffle(Seed8)

for a in range(4):
    print(Teams[a] + " = " +Seed1[a]+ " , " + Seed2[a]+ " , " + Seed3[a]+ " , " + Seed4[a]+ " , " + Seed5[a]+ " , " + Seed6[a]+ " , " + Seed7[a]+ " , " + Seed8[a])

To be clear I’m looking for something like:

for a in range(1,9):
   random.shuffle(range[a])

but that throws up an error

Asked By: Dino

||

Answers:

I would suggest putting the seeds is a list:

import random

teams = ["Alice", "Bob", "Charlie", "Delilah"]
random.shuffle(teams)

seeds = [
    ["Brazil", "Argentina", "France", "Spain"],
    ["England", "Germany", "Netherlands", "Portugal"],
    ["Belgium", "Denmark", "Uruguay", "Croatia"],
    ["Serbia", "Switzerland", "Senegal", "Mexico"],
    ["USA", "Poland", "Ecuador", "Morocco"],
    ["Wales", "Japan", "Ghana", "Canada"],
    ["Qatar", "South Korea", "Iran", "Cameroon"],
    ["Australia", "Saudi Arabia", "Tunisia", "Costa Rica"],
]
for seed in seeds:
    random.shuffle(seed)

for i in range(4):
    print(f"{teams[i]} =", ", ".join(seed[i] for seed in seeds))
Answered By: Matteo Zanoni

In the same way you do

Teams = ["Alice", "Bob","Charlie", "Delilah"]

you can do

seeds = [seed1, seed2, ...]

or even just declare it directly, skipping the seed1 = stuff and doing

seeds = [
    ["Brazil", "Argentina", "France", "Spain"],
    ["England", "Germany", "Netherlands", "Portugal"],
    ...
    ]

and then

for seed in seeds:
    random.shuffle(seed)
Answered By: Edward Peters
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.