List as function input

In Python 3.7 can items in a list be arguments to a function?

def media(x,y,z):  lista = [7,8,9]    
Author: Maniero, 2019-02-08

1 answers

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 so much sense, the ideal in case of average is already to receive an even list and not a limited number of arguments. This would give error:

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))

See working on ideone. E no repl.it. also I put on GitHub for reference futura .

 2
Author: Maniero, 2020-08-27 14:02:44