Home > Back-end >  Python - Modify for-loop variable
Python - Modify for-loop variable

Time:03-20

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:

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.

CodePudding user response:

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

CodePudding user response:

This also works if you want a short answer:

numbers = [3, 4, 6, 7]
[print(x, 5-x, 5 x, 5*x) for x in map(lambda x: x   2, numbers)]

Output:

5 0 10 25
6 -1 11 30
8 -3 13 40
9 -4 14 45

CodePudding user response:

list comprehension can work

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

CodePudding user response:

The things being done to x can be wrapped into a function. This function will perform the series of actions being done to x and print the results.

def do_things(x):
    a = 5 - x
    b = 5   x
    c = 5 * x
    print(x, a, b, c)

Then you can loop through the defined values and call the function with x unchanged

numbers = [3, 4, 6, 7]

for x in numbers:
    do_things(x)

3 2 8 15
4 1 9 20
6 -1 11 30
7 -2 12 35

Or you can modify the value of x as you call the function:

for x in numbers:
    do_things(x 2)

5 0 10 25
6 -1 11 30
8 -3 13 40
9 -4 14 45
  • Related