0

I have a variable called CurrentLineup, which contains a set of 5 names as such

set(['Player 1', 'Player 2', 'Player 3', 'Player 4', 'Player 5'])

I have a loop of all of the events during a game, which includes other players' substitutions in and out of the game.

What I would like to do is create a list of all 5 man sets as CurrentLineup updates, so I initialized the following outside of the loop... take this code as an example.

Lineup_List = []
Lineup_List.append(Current_Lineup)

For i in game_events:
    if "Enters Game" in i:
        player = 'Player 6'
        Current_Lineup.add(player)
    if "Leaves Game" in i:
        player2 = 'Player 4'
        Current_Lineup.remove(player2)
    if len(Current_Lineup) == 5:
        Lineup_List.append(Current_Lineup)

My problem is that when I return Lineup_List after the loop, it has the final version of Current_Lineup a number of times.

If this loop ran twice, I would hope for Lineup_List to have the following result:

[set(['Player 1', 'Player 2', 'Player 3', 'Player 4', 'Player 5']), 
 set(['Player 1', 'Player 2', 'Player 3', 'Player 6', 'Player 5'])]

How do I retain the various values that CurrentLineup takes through the loop, in order of occurrence?

2
  • the list stores a reference to the very same set multiple times. you can append(copy.deepcopy(myset)) to store a copy, not the original Commented Feb 7, 2017 at 18:58
  • It is probably not needed (or even desirable) to perform a deep copy. A shallow copy should be what is needed. Commented Feb 7, 2017 at 19:01

1 Answer 1

2

You need to make a (shallow) copy of the set when you append it, otherwise you just keep changing the same set, also when already referenced in the line up list. So change the last line as follows (add set()):

Lineup_List.append(set(Current_Lineup))

This appends a copy of your current line up set, so that you can safely change it in the next iterations without affecting the already added set(s).

Sign up to request clarification or add additional context in comments.

5 Comments

Thanks for your answer @trincot. I get the following error with your suggestion: TypeError: 'set' object has no attribute 'getitem'. Thoughts?
Ah, I missed the part where you said it was a set. I understood it to be a list. I updated my answer accordingly.
Sorry for the back and forth... but here's the newest error with your updated answer. "NameError: global name 'Current_Lineup' is not defined"
Your question does not have the code for the initial assignment to Current_Lineup, and you have For written with a capital, which is invalid syntax. But besides that, it works: repl.it/FaiY
Got it. Thanks so much for your help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.