Editor

Python Program to Pick Random Teams

Beginner · Games and random numbers

This program splits a list of players into random teams, the way a teacher might pick teams for a match, and chooses a captain for each. It shuffles the names with the random module and deals them out one by one, so the teams are fair and different every time.

Program

random_team_picker.py
import random
players = ["Aarav", "Diya", "Kabir", "Meera", "Rohan", "Sara", "Vikram", "Zoya", "Ishaan", "Tara"]
num_teams = 2 # or: num_teams = int(input("How many teams? "))
random.shuffle(players) # mix the names into a random order
teams = []
for t in range(num_teams):
teams.append([])
# Deal the names out like cards: one to each team in turn
for i in range(len(players)):
teams[i % num_teams].append(players[i])
for number, team in enumerate(teams, start=1):
captain = random.choice(team)
print(f"Team {number}: {', '.join(team)} (captain: {captain})")
Output
Team 1: Kabir, Zoya, Sara, Vikram, Tara (captain: Zoya)
Team 2: Diya, Rohan, Ishaan, Meera, Aarav (captain: Ishaan)

How it works

  1. random.shuffle(players) puts the list into a random order, so the teams, and the output, change on every run.
  2. teams starts as a list of empty lists, one for each team.
  3. i % num_teams goes 0, 1, 0, 1 and so on, so the names are dealt out in turn like cards and team sizes differ by at most one.
  4. random.choice(team) picks one member of each team as its captain.
  5. ", ".join(team) turns a team list into one line of names separated by commas.

Another way to write it

Using random.sample() and slicing

Using random.sample() and slicing
import random
players = ["Aarav", "Diya", "Kabir", "Meera", "Rohan", "Sara", "Vikram", "Zoya", "Ishaan"]
team_size = 3
mixed = random.sample(players, len(players)) # a shuffled copy
for start in range(0, len(mixed), team_size):
print(f"Team {start // team_size + 1}:", mixed[start:start + team_size])
print("Original list is unchanged:", players[:3], "...")
Output
Team 1: ['Aarav', 'Sara', 'Kabir']
Team 2: ['Rohan', 'Diya', 'Vikram']
Team 3: ['Ishaan', 'Zoya', 'Meera']
Original list is unchanged: ['Aarav', 'Diya', 'Kabir'] ...

random.sample() returns a new shuffled list and leaves players as it was, and slicing in steps of team_size cuts it into teams of that size.

Try it yourself

Add two more players and change num_teams to 3.

Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.

All Python programs · CBSE class 12 practical file · Python exercises