'Trying to run a for loop for a list to randomize the order without duplicates

My task is to run an NBA simulation draft. I need to print the teams with a random pick number (eg. Pick 2: Magic) and all on different lines in python. I thought I had a solid code, however, with a for loop, it will repeat teams. How can I code this so there are only 30 outputs for 30 different teams with no duplicates.

import random
fp = open("draft_results.txt", "w")
for i in range(1,31):
    rand = random.sample(nba,1)
    print("Pick", i, rand, file=fp)
fp.close()


Solution 1:[1]

2 ways you could do it:

  1. After you randomly select a team, remove them from your list
  2. Just shuffle the list

I went with #2. Also, you want close the file after the loop finishes, not within it.

import random  

fp = open("draft_results.txt", "w") 


nba = ['Atlanta Hawks','Boston Celtics','Brooklyn Nets','Charlotte Hornets',
'Chicago Bulls','Cleveland Cavaliers','Dallas Mavericks','Denver Nuggets',
'Detroit Pistons','Golden State Warriors','Houston Rockets','Indiana Pacers',
'Los Angeles Clippers','Los Angeles Lakers','Memphis Grizzlies','Miami Heat',
'Milwaukee Bucks','Minnesota Timberwolves','New Orleans Pelicans',
'New York Knicks','Oklahoma City Thunder','Orlando Magic','Philadelphia 76ers',
'Phoenix Suns','Portland Trail Blazers','Sacramento Kings','San Antonio Spurs',
'Toronto Raptors','Utah Jazz','Washington Wizards']

    
random.shuffle(nba)
for i, team in enumerate(nba, start=1): 
    print(f"Pick {i}: {team}", file=fp) 
fp.close()

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 chitown88