Python style advice

Nick Craig-Wood ncw at axis.demon.co.uk
Mon Feb 9 16:41:18 EST 2004


Python newbie advice needed!

I'm tring to write what I would have expressed in Perl as

    my ($a, $b, $c) = @array;

This is very similar to the python statement

    a, b, c = array

BUT, the Python will throw an exception if array isn't exactly 3
elements long, wheras the Perl will work for any length of @array,
either throwing away excess elements or setting the variables to
undef, ie like this

    if len(array) >= 1:
       a = array[0]
    else:
       a = None
    if len(array) >= 2:
       b = array[1]
    else:
       b = None
    if len(array) >= 3:
       c = array[2]
    else:
       c = None

This works if array has >= 3 elements

    a, b, c = array[:3]

And this works however many elements array has

    a, b, c = (array + 3*[None])[:3]

but it doesn't seem very Pythonic - is there a better way?

-- 
Nick Craig-Wood
ncw at axis.demon.co.uk



More information about the Python-list mailing list