Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function parameters, list and int in python

i'm trying to write a function that takes a list and a int as its arguments.

functionName(*args, number)
   #do stuff

number needs to be an int but i keep getting a syntax error in IDLE (that's the IDE i'm using)

like image 440
andy Avatar asked Apr 11 '26 16:04

andy


2 Answers

If your first argument is to be a list, remove the *:

def functionName(listob, number):

The *args syntax is used to catch an arbitrary number of positional arguments and must be listed after all other positional (and keyword) arguments:

def functionName(number, *args):

because it allows your function to be called with just the number, or with any number of extra arguments; functionName(42, 'foo', 'bar') results in number = 42 and args = ('foo', 'bar'). That's not the same as passing in a list object however.

Python doesn't otherwise constrain the types of objects that can be passed in; *args would present extra arguments to your function as a tuple, but only because that's the best way to represent 0 or more arguments extra passed into your function.

like image 160
Martijn Pieters Avatar answered Apr 13 '26 05:04

Martijn Pieters


You cannot have *args before an actual argument. So you can call it like this:

def foo(name, *args)

However, you want a list, so there's no need for *args. Having the following signature will do just fine:

def foo(name, lst)
like image 45
Games Brainiac Avatar answered Apr 13 '26 06:04

Games Brainiac



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!