Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Pass a tuple of integers to range() function

I’m trying to check if a number is in an interval of numbers using

if number in range(2010, 2020)

However I would like to store (2010, 2020) in a tuple with meaningful variable name:

VALID_YEARS = (2010, 2020)
if number in range(VALID_YEARS)

which returns an error:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

TypeError: 'tuple' object cannot be interpreted as an integer

I know it’s possible to

valid_start_year = 2010
valid_end_year = 2020
if number in range(valid_start_year, valid_end_year)

but for me using a tuple would be more "concise".

Is it possible? How?

>Solution :

You’re looking for the unpacking operator:

VALID_YEARS = (2010, 2020)
number = 2015
if number in range(*VALID_YEARS):
    print('yep')

Similarly, you can also unpack dictionaries to serve as parameters to a function (for example), but you need the double star:

d = {'a': 1, 'b': 2}


def fun(a, b):
    print(f'{a} and {b}')


fun(**d)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading