pythonlistinitializationset

Initialize a python list with unique sets


I just realized that these two behave differently

a = [set()] * 3

b = [set(), set(), set()]

a's elements will be the same instance of the set, i.e.

a[0] is a[1] is a[2] is true

b's elements will all be different instances of the set.

b[0] is b[1] is b[2] is false

I am wondering if there exists a technique to initialize a list with unique instances of sets in a smart way.

Or is this the only way:

a = []
for i in range(3):
    a.append(set())

Solution

  • You could use a list comprehension:

    b = [set() for i in range(3)]
    

    Since the expression set() is evaluated for each iteration in the list comprehension, you get 3 distinct sets.