Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a function that takes a list or integer as argument (Python)

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.

like image 773
sfowler12 Avatar asked Aug 01 '26 19:08

sfowler12


2 Answers

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
like image 185
Padraic Cunningham Avatar answered Aug 04 '26 07:08

Padraic Cunningham


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))
like image 35
ch3ka Avatar answered Aug 04 '26 08:08

ch3ka



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!