In Python, how can I check if *args[0] exists?
def my_fxn(self, *args):
print(args[0])
my_fxn('ABC') # this prints 'ABC'
my_fxn() # this crashes with "IndexError: tuple index out of range"
If you work with *args
, *args
will be a tuple (with zero, one or more elements). The truthiness of a tuple is True
if it contains at least one element. So you can simply write:
def my_fxn(self, *args):
if args:
print(args[0])