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

Python – Modify for-loop variable

I got this function:

numbers = [3, 4, 6, 7]

for x in numbers:
    a = 5 - x
    b = 5 + x
    c = 5 * x
    print(x, a, b, c)

What it exactly does doesn’t matter, only the x is relevant.

I want modify x so that:

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

for x in numbers:
    a = 5 - (x + 2)
    b = 5 + (x + 2)
    c = 5 * (x + 2)
    print((x + 2), a, b, c)

But obviously adding + 2 everywhere is annoying, so I just want to have another value for x.

Ofcourse I could make another variable like this:

for x in numbers:
    modifiedX = x + 2
    a = 5 - modifiedX
    b = 5 + modifiedX
    c = 5 * modifiedX
    print(modifiedX, a, b, c)

But I’m curious if I could get the same result without adding another line, like:

for x + 2 in numbers:
    a = 5 - x
    b = 5 + x
    c = 5 * x
    print(x, a, b, c)

or this:

x + 2 for x in numbers:
    a = 5 - x
    b = 5 + x
    c = 5 * x
    print(x, a, b, c)

Both of these last 2 code blocks aren’t correct Python syntax, so I’m curious:
Is there is a correct method out there to have a modified version of x without adding more lines?

Note: I still want to keep the original numbers list, so Im not looking for changing the numbers in the list directly.

>Solution :

You can use map() to generate a new iterable that contains the elements of numbers incremented by 2. Since map() creates a new iterable, the original list isn’t modified:

numbers = [3, 4, 6, 7]

for x in map(lambda x: x + 2, numbers):
    a = 5 - x
    b = 5 + x
    c = 5 * x
    print(x, a, b, c)

This outputs:

5 0 10 25
6 -1 11 30
8 -3 13 40
9 -4 14 45
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