Question

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?

Was it helpful?

Solution

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'

OTHER TIPS

Yes, it is pythonic. In fact, Raymond Hettinger talks about this in his excellent talk, Transforming Code into Beautiful, Idiomatic Python. It's a good talk to watch if you're interested in writing pythonic code.

To answer your second question, I like to read the source of the python standard library. Most of the modules are very well written, as you might expect. The collections module, for example, is nice to read.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top