2

Here is simple example of checking variable across multiple values:

var = "a"
if var == "a" or var == "b" or var == "c":
    print("true")
else:
    print("false")

After a small reseach, I found another, more advanced approach by Martijn Pieters:

var = "a"
if var in {"a", "b", "c"}:
    print("true")
else:
    print("false")

But also, in the link I posted above, it is stated that brackets are also acceptable:

if var in ("a", "b", "c"):

What is the difference between curly brackets {...} and (...) brackets here?

And if it is possible to answer, what is the best?

Community
  • 1
  • 1
john c. j.
  • 725
  • 5
  • 28
  • 81

2 Answers2

2

{...} creates a set while (...) will create a tuple for you (the actual tuple creation token is the comma (,)). For small data, there is probably no perceptible difference.

When doing an in check with a set, the hash value of the var is calculated and used as basis for an index while when doing a membership test with a tuple, the tuple is searched from start till var is found or not found.

cobie
  • 7,023
  • 11
  • 38
  • 60
1

The first, i.e {...} denotes/creates a set, using in with a set you'd be performing a set membership operation which results in O(1) complexity.

(...), on the other hand, denotes/creates a tuple. Searching for membership with in in a tuple is O(N) since it goes through every element in the tuple perfoming a check to see if there's a match.

In a small case such as your, this arguably won't make much of a difference (unless in a tight loop). In general, you should prefer {...} since it isn't really harder to type and has the perk of being efficient.

Dimitris Fasarakis Hilliard
  • 150,925
  • 31
  • 268
  • 253