Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is a, b = b, a + b good python? [closed]

a, b = b, a + b 

I picked up this coding style from 'Building Skills in Python'. Coming from PHP and Obj-C this type of multi-variable assignment wasn't available (at least not that I've seen). But it seems more logical to me. Afterall, why should I have to assign 'a' to a 'holding variable' before it is replaced.

Question is, is this coding style pythonic?

Here's a sample Fibonacci program:

a, b = 1, 2
output = str(a)
while b<=100:
    output = output + " " + str(b)
    a, b = b, a + b

print output

And, what's the best way you found helped you write more pythonic code?

like image 964
snowbound Avatar asked Dec 15 '22 00:12

snowbound


1 Answers

The tuple unpacking is pythonic, but some other parts of your snippet aren't. Here's a slight modification using a generator to avoid (and separate) the string concatenation:

def fib(k=100):
    """ Generate fibonacci numbers up to k. """
    a, b = 1, 2
    while a <= k:
        yield a
        a, b = b, a + b

print(' '.join(map(str, fib())))
# prints: '1 2 3 5 8 13 21 34 55 89'
like image 90
miku Avatar answered Dec 17 '22 13:12

miku