Reputation: 101
In the code below I want to creat a string list and I pass a variable min to a method as an argument:
max_list = [1 , 2 , 3]
min = 0
output = ["{a} + {b}".format(a=min, b=max) for max in max_list]
However, I want to increment min every time I generate a list object. Is there a python way to achieve the same result of ++ operator? Apparently, I can't use min++ in this case as it is python code.
Expected Result:
['0 + 1', '1 + 2', '2 + 3']
Upvotes: 0
Views: 361
Reputation: 32073
Since Python 3.8 you can use assignment expression :=
. But since the increment will occur before the return of the expression result like ++min
, you need to initialize min
to -1
max_list = [1 , 2 , 3]
min = -1
output = ["{a} + {b}".format(a=(min := min + 1) , b=max) for max in max_list]
Upvotes: 0
Reputation: 1570
You didn't share your expected output so this may not be what you wanted, but...
max_list = [1, 2, 3]
output = [f"{min} + {max}" for min, max in enumerate(max_list)]
print(output)
Output:
['0 + 1', '1 + 2', '2 + 3']
Upvotes: 3
Reputation: 36360
Firstly min
and max
are unfortunate variable names in python, as they shadow built-in min
and max
functions. As for increasing by 1 you might harness itertools.count
following way:
import itertools
max_list = [1 , 2 , 3]
mn = itertools.count(0)
output = ["{a} + {b}".format(a=next(mn), b=mx) for mx in max_list]
print(output)
Output:
['0 + 1', '1 + 2', '2 + 3']
Upvotes: 1