Search code examples
pythonlistnewlineiterable-unpacking

How do you include newlines in a python list unpack?


for row in rows:
    a, b, c = row

is nice but

for row in rows:
    alpha, beta, charlie, delta, echo, foxtrot, gamma, horseshoe, indigo, jimmy, killshot = row

is not very nice. Python is usually good about supporting newlines after commas but I can't figure out the syntax for this one. Something like this would be nice:

for row in rows:
    alpha, 
    beta, 
    charlie, 
    delta, 
    echo, 
    foxtrot, 
    gamma, 
    horseshoe, 
    indigo, 
    jimmy, 
    killshot = row

What is the PEP 8 way to handle this, since long lines are anti-PEP 8?


Solution

  • Use parentheses:

    for row in rows:
        (alpha, 
         beta, 
         charlie, 
         delta, 
         echo, 
         foxtrot, 
         gamma, 
         horseshoe, 
         indigo, 
         jimmy, 
         killshot) = row
    

    Personally, I'd probably use more than one item per line (breaking where the lines get long, or where there's a logical change in the meaning of the items), but as long as you're consistent I think the style above would be fine too.