Python - Set Immutable constraints

Introduction

Sets can only contain immutable object types.

Hence, lists and dictionaries cannot be embedded in sets, but tuples can if you need to store compound values.

Tuples compare by their full values when used in set operations:

Demo

S = set()                    # Initialize an empty set 
S.add(1.23) # www  .  ja  v  a2 s  .c om

print( S )
#S.add([1, 2, 3])                   # Only immutable objects work in a set 
S.add({'a':1}) 
S.add((1, 2, 3)) 
print( S )                                  # No list or dict, but tuple OK 
print( S | {(4, 5, 6), (1, 2, 3)} )         # Union: same as S.union(...) 
print( (1, 2, 3) in S )                     # Membership: by complete values 
print( (1, 4, 3) in S )

Result

Related Topic