list unpack trick?

Fredrik Lundh fredrik at
Sat Jan 22 02:34:27 EST 2005

"aurora" wrote:

> The only issue is when s does not contain the character '=', let's say it  is 'xyz', the result 
> list has a len of 1 and the unpacking would fail. Is  there some really handy trick to pack the 
> result list into len of 2 so  that it unpack as name='xyz' and value=''?

do you need a trick?  spelling it out works just fine:

        key, value = field.split("=", 1)
        key = field; value = ""


    if "=" in field:
        key, value = field.split("=", 1)
        key = field; value = ""

(the former might be slightly more efficient if the "="-less case is uncommon)

or, if you insist:

    key, value = re.match("([^=]*)(?:=(.*))?", field).groups()


    key, value = (field + "="["=" in field:]).split("=", 1)

but that's not really worth the typing. better do

    key, value = splitfield(field)

with a reasonable definition of splitfield (I recommend the try-except form).

> So more generally, is there an easy way to pad a list into length of n  with filler items appended 
> at the end?

some variants (with varying semantics):

    list = (list + n*[item])[:n]


    list += (n - len(list)) * [item]

or (readable):

    if len(list) < n:
        list.extend((n - len(list)) * [item])



More information about the Python-list mailing list