Feb-18-2022, 07:49 PM
Quote:Wouldn't this be easier players = [Player()] * xNope. If you do this you end up with 1 player. players[0] would be the same player as players[1] and so on. This is a common problem where programmers try to create a list of mutable objects using the "*" operator.
Nobody complains if "numbers = [0] * count" returns a list where numbers[0] is numbers[1], but it is usually not the desired result when trying to make a list of lists. "lists = [[]] * count" works exactly the same as "numbers", where lists[0] is lists[1]. In both cases you have a list holding a single value that is used to create a list holding multiple of the value. if you want a different value for each item in the list you need a different generator.
To make a list containing different numbers you might do this
numbers = [number for number in range(count)]To build a list of different lists you do this:
lists = [[] for _ in range(count)]And to build a list of different players you do this:
players = [Player() for _ in count]