0

I wanted to make a list of empty sets for my program. This works for making a list of unique zeros.

x=5
l=[0]*x
print(l)
m[0]=1
#[1,0,0,0,0]

If you try the same with sets or a list of list it doesn't work.

x=5
l=[set()]*x
l[0].add(1)
print(l)
#[{1},{1},{1},{1},{1}]

The same happens with lists.

x=5
l=[[]]*x
l[0]+=[1]
print(l)
#[[1],[1],[1],[1],[1]]

The only work around I've found is using range(). My question is there a different way of doing this I don't know about? It seems like I'm missing something.

x=5
l=[[] for i in range(x)]
l[0].add(1)
print(l)
#[[1],[0],[0],[0],[0]]
Michael Hearn
  • 557
  • 6
  • 18
  • 3
    The "work around" you've found is not a work around, it's the right way. Use that. – wim May 22 '23 at 18:58
  • 1
    You've done a list comprehension with a generator expression in your last example, which is the right way to create a list of unique sets. This way, a new set (or list) is created for each iteration, and they are independent objects: x = 5 l = [set() for _ in range(x)] l[0].add(1) print(l) # prints [{1}, {}, {}, {}, {}] like was list x = 5 l = [[] for _ in range(x)] l[0].append(1) print(l) # prints [[1], [], [], [], []] – varshneydevansh May 22 '23 at 19:01
  • 1
    Yes, You have the right idea with list comprehension as python zen suggests explicit is better than implicit. But you can acheive the same behavior with [{0}] * 5 . The reason this works is because when you multiply a number by 5 you get a number that is 5 times as large, you will not get 5 numbers. same with [{0}) * 5 you get {0} five times, not [{0}] five times – araldhafeeri May 22 '23 at 19:08
  • Thanks the title on https://stackoverflow.com/questions/240178/list-of-lists-changes-reflected-across-sublists-unexpectedly List of Lists changes reflected across sublists unexpectedly doesn't come up easily in searches. – Michael Hearn May 22 '23 at 19:35
  • 3
    @araldhafeeri `[{0}] * 5` gives a list with 5 references to the same set object. So that would cause the same undesired behaviour as with the other "wrong" examples that OP showed in the question. – slothrop May 22 '23 at 19:43

0 Answers0