Search code examples
pythontuplesiterable-unpacking

Is there a simple pythonic way to increase variables while unpacking a tuple?


I want to do something like:

a,b,c,d = 1,2,3,4
a,b,c,d += 2,4,6,8

But this does not work. I know I can increase them individually but I thought there would be a simpler way. The only alternative I came up with was this ugly list comprehension:

a,b,c,d = [j+k for idxj,j in enumerate((a,b,c,d)) for idxk,k in enumerate((2,4,6,8)) if idxj==idxk]

Is there a better way?


Solution

  • zip, generally:

    a, b, c, d = [x + y for x, y in zip((a, b, c, d), (2, 4, 6, 8))]
    

    but there’s also our friend the semicolon:

    a += 2; b += 4; c += 6; d += 8
    

    Replace with a newline at your discretion.