JoJ3o
JoJ3o

Reputation: 25

Python - Modify for-loop variable

I have 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.

Of course, 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)

The 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 I'm not looking for changing the numbers in the list directly.

Upvotes: 2

Views: 123

Answers (4)

user12842282
user12842282

Reputation:

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

Upvotes: 0

necaris15
necaris15

Reputation: 11

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)

Upvotes: 0

catasaurus
catasaurus

Reputation: 976

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

Upvotes: 0

BrokenBenchmark
BrokenBenchmark

Reputation: 19262

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

Upvotes: 3

Related Questions