Reputation: 35
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.
Upvotes: 3
Views: 18621
Reputation: 477
The if portion in your code i.e. if type(args) is list:
is never going to be executed. Because, whenever non-keyword arguments are passed to a function using *args
, the value received as args
is always a tuple. So type(args) is list
is always going to be False
. What needs to be done is iterate through the arguments passed through *args
and check if the type of argument, if it's list then you have passed a list i.e. average([1,3,5,7])
else it will be integer when integers are passed i.e. average(1,3,5,7)
. So following piece of code will work :-
def average(*args):
for x in args:
if type(x) == list:
# List is passed
return sum(x) / float(len(x))
# Assuming inputs passed restricted to list and numbers
# Numbers are passed as argument
return sum(args) / float(len(args))
Here this will provide you the output for both types of input :-
>>> average([1,3,5,7])
4.0
>>> average(1,3,5,7)
4.0
Upvotes: 0
Reputation: 180540
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
Upvotes: 6
Reputation: 22998
def average(*args):
if type(args) is tuple:
r = 0
for x in args:
for y in x:
r += y
print r / float(len(x))
else:
print sum(args) / float(len(args))
average([2, 3, 8, 1, 9])
Upvotes: 1
Reputation: 12178
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))
Upvotes: 1