I'm trying to create a function that gives the average of either a list of numbers or just integers as variables. So far I have:
def average(*args):
if type(args) is list:
for x in args:
print sum(x) / float(len(x))
else:
for x in args:
args = list(args)
print sum(x) / float(len(x))
When I input a list, like
average([1, 3, 5, 2])
it works great. But when I enter in
average(1, 3, 5, 2)
it gives "TypeError: 'int' object is not iterable". I've checked other questions but none of the solutions seem to work. I've tried to check if it's a list with type() and isinstance() but whenever I get one of them to work, the other throws out an error.
args is a tuple so check if args[0] is a list the sum the contents of args[0], if just ints are passed in just sum args:
def average(*args):
if isinstance(args[0],list):
print(sum(args[0]) / float(len(args[0])))
else:
print (sum(args) / float(len(args)))
In [2]: average(1, 3, 5, 2)
2.75
In [3]: average([1, 3, 5, 2])
2.75
If you want to accept tuples,use collections.Iterable:
from collections import Iterable
def average(*args):
if isinstance(args[0],Iterable):
print(sum(args[0]) / float(len(args[0])))
else:
print (sum(args) / float(len(args)))
In [5]: average([1, 3, 5, 2])
2.75
In [6]: average(1, 3, 5, 2)
2.75
In [7]: average((1, 3, 5, 2))
2.75
the second print sum(x) / float(len(x)) calls len() on x, which is an integer.
I think you mean something like:
else:
print sum(args) / float(len(args))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With