List as function input

Asked

Viewed 92 times

1

In Python 3.7 items of a list can be arguments of a function?

def media(x,y,z):  lista = [7,8,9]    

1 answer

2


Well, this code doesn’t seem to make much sense, but I imagine this is what you want:

def media(x, y, z):
    return (x + y + z) // 3 
lista = [7, 8, 9]
media(*lista)

Note that this particular example does not make much sense, the ideal in the case of average is to receive a list even and not a limited number of arguments. This would be a mistake:

print(media(*[8, 9]))
print(media(*[6, 7, 8, 9]))

This looks more like what you want:

def media(*lista):
    soma = 0
    for i in lista:
        soma += i
    return soma // len(lista)
lista = [7, 8, 9]
print(media(*lista))

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

  • Thank you very much!. It is part of an exercise that I am practicing. I put only a piece, which took away my sleep, to continue with others.

  • In the displayed code of the function the * usage for the list parameter can be omitted. If this is done, in the last line, when the media is printed, you should not use * either.

  • @Pa seems to me not to be true, I test and gave error.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.