0

I saw this piece of code being used to iterate over a 2D list column-wise:

"""
grid: List[List(int)]
"""
for col in zip(*grid):
    ...

Could someone explain exactly how this works?

EDIT:

Duplicate of this question, but not this one.

I still don't understand exactly how zip(*_) converts rows into columns.

andrey
  • 1,515
  • 5
  • 23
  • 39
  • 2
    if `grid` looks like `[[1,2,3], [7, 8, 9]]`, then `zip(*grid)` looks like `zip([1,2,3], [7, 8, 9])`. Does it make sense why that transposes rows to columns? – Adam Smith Apr 24 '18 at 23:26
  • 1
    This has more to do with [inverse function of zip](https://stackoverflow.com/a/13635074/1586200). If the question reopens, I can write an answer. You can experiment by yourself too. Just do: `a = [[1,2,3], [4,5,6]], print zip(*a)`. You can also read [this](https://medium.com/@happymishra66/zip-in-python-48cb4f70d013). – Autonomous Apr 24 '18 at 23:26

0 Answers0