Search code examples
pythonlistfor-loopunpack

Python: how to unpack more than one value in a for?


I'm trying to unpack two values in a for:

def getDiagonal(self):
    diagonal = [(r, c) for (r,c) in range(0, len(self.matrix)), range(0, len(self.matrix[0]))]
    return diagonal

And gives this error:

    Traceback (most recent call last):
  File "matrixModule.py", line 4, in <module>
    print m.getDiagonal()
  File "C:\Users\Capinzal\Google Drive\ProgramaþÒo\Matrix\matrix.py", line 46, in getDiagonal
    diagonal = [(r, c) for (r,c) in range(0, len(self.matrix)), range(0, len(self.matrix[0]))]
ValueError: too many values to unpack

Solution

  • With zip():

    diagonal = [(r, c) for (r,c) in zip(range(len(self.matrix)), range(len(self.matrix[0])))]
    

    That said, if you just want the tuple anyway, there's no need to unpack it or even make a comprehension, although you would still need zip():

    diagonal = list(zip(range(len(self.matrix)), range(len(self.matrix[0]))))
    

    You can also omit the 0 for the range object, as that's the default start value. You'd need it if you wanted to specify a custom step value.