Emad
Emad

Reputation: 23

Arguments in a function

I understand that when defining a function, you can provide a parameter, like so:

def func(lst):
    # code 

I also understand that when you are defining a function, you can provide multiple parameters using the *args syntax, like so:

def func(*lst):
    # code

I have a problem where I have to define a function that sorts a list and removes any duplicates.

Here's what I did:

def func(lst):
    return sorted(set(lst))

The website that I was doing this practice problem (edabit.com) tested my code, like so:

Test.assert_equals(func([1, 3, 3, 5, 5]), [1, 3, 5])

The test ran successfully, and my code was correct. But here's where I got confused, the test provided multiple parameters (1, 3, 3, 5, 5), I didn't use the *args syntax, yet somehow it ran successfully.

Isn't it supposed to give me an error, saying something like func() takes exactly 1 argument (5 given)?

When I provided the *args syntax, it told me TypeError: unhashable type:'list'

My guess is that this probably happened because the test didn't call the function, instead they used the assert keyword. Is my guess correct?

Upvotes: 0

Views: 57

Answers (3)

Kevin Hoopes
Kevin Hoopes

Reputation: 507

It looks like they only did pass a single parameter to your function.

Test.assert_equals(func([1, 3, 3, 5, 5]), [1, 3, 5]))

The array [1, 3, 3, 5, 5] is passed as the single argument to func(), then the array [1, 3, 5] is passed as the second argument to assert_equals().

Upvotes: 1

DownloadPizza
DownloadPizza

Reputation: 3456

No, you gave a single argument of type list. If you have a = [1,2,3,4] You have a list Calling f(a) And f([1, 2,3,4]) is the same Notice the [ brackets. If, however, you were too call f(1, 2,3,4), that would be a mistake.

Also: the assert keyword still calls the function. It has no way of not calling it, as it has been put in as an expression. if you call f(g(5)) Then f is already called with the result of g, not the function call itself.

Upvotes: 1

A.J. Uppal
A.J. Uppal

Reputation: 19264

You passed in a list of numbers, which is one argument:

func([1, 3, 3, 5, 5])

vs.

func(1, 3, 3, 5, 5)

Upvotes: 1

Related Questions