[Tutor] Mathematical operations on a list
Cameron Simpson
cs at cskk.id.au
Wed Oct 20 19:00:30 EDT 2021
On 20Oct2021 21:59, JUDE EJEPU <ejepujude at gmail.com> wrote:
>Sir,
>I created a function to calculate a variable G
>def gfactor(dist,electro):
> G = pie_value() * (dist**2 - electro**2)/(2*electro)
> return G
This is good, a function of 2 numbers.
>However, when I passed a list of arguments,:
>x = [1, 2, 3]
>y = [0.5, 0.5, 1]
>gFactor(x,y), I got an error
You're handing it lists. They are not numbers!
Please describe what result you _wanted_ to receive from this call.
I would not change the function at all.
Instead, guess at what you might want as being the equivalent of:
[ gFactor(1, 0.5), gFactor(2, 0.5), gFactor(3, 1) ]
you would need to pair up the elements of your 2 lists and then call
gFactor() with each pair.
_Please_ rename x and y to something else to indicate that they are
lists and not numbers, for example "xs" and "ys", which I will use below
to avoid confusion.
Python has a zip() builtin method to pair up lists (it will do more than
pairs if you have more lists, BTW). So:
paired = zip(xs, ys)
which would get you an iterable of pairs. You can then iterate over
that:
for x, y in paired:
gFactor(x, y)
You probably want these as a list. You could do that like this:
gs = []
for x, y in paired:
gs.append( gFactor(x, y) )
or more directly with a list comprehension:
gs = [
gFactor(x, y) for x, y in paired
]
which does the same thing.
Cheers,
Cameron Simpson <cs at cskk.id.au>
More information about the Tutor
mailing list