Home > OS >  Best practice to write sequence constants as tuple? And as set when testing for inclusion?
Best practice to write sequence constants as tuple? And as set when testing for inclusion?

Time:06-29

If we have small sequence constants in our code, is it best practice to write them as tuple rather than as a list? Or does it not really matter?

e.g. ORDER_TYPES = (1, 2, 3) vs ORDER_TYPES = [1, 2, 3]

And when we intend to use inclusion operations against that sequence, does it make sense to store as a set?

e.g.

ORDER_TYPES = {1, 2, 3}
order_type = 1
if order_type in ORDER_TYPES:
    ...

Are there any actual speed/space benefits to storing as tuple vs list, or as a set, when the sequences are small like this? I know this falls into the realm of over-optimizing but just wondering what is actually considered best practice.

CodePudding user response:

Using tuples is recommended,

Actually in your case there not much difference as they are not too many and they are not being used a lot.

but when you mentioned best practice in your question although you can(allowed) to use any data structure evens strings but there is no difference between your question and general best practice cases.

so take a close look at This link or other similar links.

Also Here explains with more details.

CodePudding user response:

The main difference between lists and sets are the efficiency mainly in operations like in. For example:

l = [1, 2, 3]
s = {1, 2, 3}

print(1 in l, 1 in s)

In this case, using a set is much more efficient than a list because sets work with hash maps on the low level, so it will have O(1) time complexity for checking if an element is contained in a set. Meanwhile, lists and tuples take O(n) complexity, which is much more expensive. Also, using set allows you to insert elements in O(1) complexity too.

You can learn more about both structures with this resource.

  • Related