Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

+= with multiple variables in python [closed]

I'm trying to increment multiple variables at the same time and stick it into one line. What would be the most pythonic way to do this if there is a way?

like image 947
user3255511 Avatar asked Jan 31 '14 00:01

user3255511


2 Answers

If you want to write a single line, you can try multiple assignment, but without the += syntax:

a, b, c = a+1, b+1, c+1

Or for a more pythonic solution, avoid the one-liner:

a += 1
b += 1
c += 1
like image 50
Óscar López Avatar answered Nov 05 '22 13:11

Óscar López


Say you have

a, b, c = [1, 2, 3]

after you define:

def add1(x):
    return x+1

You can do:

print(map(f,[a, b, c])) # prints [2, 3, 4]

which means that the following line will give you what you want:

a, b, c = map(add1,[a, b, c])

which is a bit easier to do than:

a, b, c = a+1, b+1, c+1

in case you have a big array. Further, you maintain readability and get your "one liner".

like image 45
Nir Alfasi Avatar answered Nov 05 '22 14:11

Nir Alfasi