Search code examples
pythonpython-3.xpython-2.7matrix-indexing

How to skip the index when the indexing goes out of range [Python]


My matrix is :

[['f', 'e', 'e', 'd'], ['t', 'h', 'e', 'd'], ['o', 'g']]

Code :

for i in range(cols):
            result = ""
            for j in range(rows):
                result += matrix[j][i]
            temp.append(result)
        return(" ".join(temp))

When I am running the loop, which needs to capture elements row-wise, it throws an error as soon as the element (row = 3, col = 3) in the last row is reached which is not present. Is there any way I can skip the element that is not present by giving any condition like skip if an index does not exist and move on with the next first row again?


Solution

  • You could surround your code in a try...except block

    try:
        result += matrix[j][i]
    except IndexError: 
        pass