Home > Software engineering >  How to apply a function to each element of a list without for loops or lambda functions?
How to apply a function to each element of a list without for loops or lambda functions?

Time:08-31

For example, let's say I have a list:

integer_list = [1, 2, 3, 4]

and I want to plug each element of the list into a formula, like (x*5) 1. How would I do that? I cannot use for loops or lambda functions. I can't import any modules either. Right now I am quite literally doing integer_list[0] * 5 1 How would I then get the answer from that and multiply every item in the set by it?

Please help!

CodePudding user response:

no lambda no cry

def f(x):
    return (x*5) 1

result = list(map(f, integer_list))

CodePudding user response:

Using a for loop should be the right and simplistic solution

integer_list = [1, 2, 3, 4]

for (let i = 0; i < integer_list.length; i  ){
  console.log((i*5) 1)
}

like so.

Alternatively, you could use the forEach() method

integer_list.forEach(num => console.log((num*5) 1))

one line of code. The forEach() method takes in a callback function, then you pass an argument to the function, you can now loop through the array using the argument as the index. Hope this was helpful.

  • Related