pythoniterable-unpacking

How to unpack only some arguments from zip, not all?


My SQL query:

select id,value,zvalue from axis

gives me result like this:

ans=(1,23,34)(12,34,35)(31,67,45)(231,3412,234)

now if I want all these 3 variables as 3 different lists

id, value, zvalue = zip(*ans)

But if I only want id and value as separate lists. It will give me too many values to unpack error.

id, value = zip(*ans)

Is there any way where I can create any number of lists from SQL query. Because if there are 10 parameters in the query, I have to use all the parameters while using ZIP?


Solution

  • The number of arguments must match, this is a rule in Python 2. For Python 3, you can use * to capture into a list.

    The common pythonic (2.x) workaround is to use _ to denote variables you won't use, i.e.:

    id,value,_ = zip(*ans) # only works for exactly three values
    

    As DSM commented, for Python 3, you can use * to grab "remaining" args as a list:

    id, value, *_ = zip(*ans) # _ will be a list of zero or more args
    

    Or, simplest, just slice the return from zip:

    id,value = zip(*ans)[:2] # ignore all but first two values