Woody1193 Woody1193 - 3 months ago 19
Python Question

Set membership in Python

I have a tuple x such that

x = (1, 2)
and I have a set z. Suppose I do this:

z = set(x)
1 in z # True
2 in z # True
x in z # False


Why does this happen and how can I add tuples to a set and preserve their properties as tuples?

Answer

Try doing any of these instead:

  • z = {x}
  • z = set([x])
  • z = set(); z.add(x)
  • z = set(); z.update([x])