Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

"step by step" applying a function to each element of a list

There’s code:

nums = [1, 2, 3, 4]
def func(a):
    return 10 * a

result = list(map(func, nums))
print(result)

With result:

[10, 20, 30, 40]

How to apply a function to the first element of the list, show the result, and then apply to the others in the same way?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

And the result should look something like this:

10
20
30
40

>Solution :

You would need a loop for this since list(map()) will return the full list rather than print "one by one"

nums = [1, 2, 3, 4]
def func(a):
    return 10 * a

for n in nums:
    print(func(n))

Or this, which will also run your func and print the returned value, one value at a time

nums = [1, 2, 3, 4]
def func(a):
    return 10 * a

for n in map(func, nums):
    print(n)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading