nluizsoliveira
nluizsoliveira

Reputation: 375

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:

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?

Upvotes: 1

Views: 1301

Answers (1)

Grismar
Grismar

Reputation: 31354

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)

Upvotes: 4

Related Questions