Home > Software design >  Running for-loop and trying to multiply list items
Running for-loop and trying to multiply list items

Time:09-17

I am trying to run the equation for all the items in the given list (here 3,4,1) in the for loop. Idea is to use a number from list a and a number from range (index number for the list).

So the first one goes ok, 3 * 3^2 3 5 = 35. This should run through all the items in the list and return [[35, 57, 9]] but gives [[35, 4, 1]] instead. I know it does not run all three items, but what's the thing here I'm missing.

def calculate_f(a):

    i=0
    lis = []

    for x in range(0, len(a)):
        
        a[i] = 3 * (a[i]**2)   a[i]   5

        lis.append(a)
        
        i  = 1

        return lis

a = [3,4,1]  
calculate_f(a)

Been doing this for three hours and got this far from different error messages, but this almost works :D

Thanks

CodePudding user response:

Try this:-

def calculate_f(a):
    return [3 * x ** 2   x   5 for x in a]
 
print(calculate_f([3,4,1]))

CodePudding user response:

In Python, if you want to apply a function to a list of values there are many simpler ways to do it.

First define your function on a single element:

>>> def f(x):
...     return 3 * x**2   x   5

Now there are many ways you can "map" this function to list of values. For example the built-in map():

>>> m = map(f, [3, 4, 5])
>>> m
<map at 0x7f6aa8b00150>

This in fact returns an iterable map object that can return each value one at a time:

>>> next(m)
35

Or you can pass it to list():

>>> list(map(f, [3, 4, 5]))
[35, 57, 85]

Or you can use a simple for loop if you want to get more comfortable with that:

>>> m = []
>>> for x in [3, 4, 5]:
...     m.append(f(x))

Or the more advanced/succinct version, a list comprehension:

>>> m = [f(x) for x in [3, 4, 5]]
>>> m
[35, 57, 85]

Or, if you eventually want fast element-wise numerical calculations, get familiar with NumPy arrays:

>>> import numpy as np
>>> f(np.array([3, 4, 5]))
array([35, 57, 85])
  • Related