Search code examples
pythonexcelloopsfor-loopnested-loops

Storing values in different variables in nested for loop


I'm currently writing a piece of code that loops through the rows and columns of a spreadsheet and then uses the value of the cell at row r and column c in the parameter of a function. I currently have it working as following:

for i in range (1, ws.max_row+1): 
    first_column = worksheet.cell(i,1).value
    second_column = worksheet.cell(i,2).value
    third_column = worksheet.cell(i,3).value
    result = functionX.create(first_column, second_column, third_column)

Where the index i loops through the rows in the sheet. I'm using the worksheet.cell(row,column).value function from the openpyxl library and store them in the x_column variables. Later, these variables get used as parameters in the class.create() function within the same for loop.

However, what I would like to do is to keep track of the columns in the loop as well, with a separate index. Reason for this is that I would like to print out a message to the user when he an empty cell has been encountered at row i and column j.

As a solution, I thought it could be useful to use a nested for loop to keep track of the columns:

for i in range (1, ws.max_row+1):
    for j in range (1,4):
        first_column = worksheet.cell(i,j).value
        second_column = worksheet.cell(i,j).value
        third_column = worksheet.cell(i,j).value
    result = functionX.create(first_column, second_column, third_column)

However, this will obviously not increment the index j within the same iteration of the second loop. Any idea how to solve this?


Solution

  • If you really want to use a for loop for the columns, you could use a list to gatter the values of the cells and then unpack that list to pass the gattered values to the method .create().

    This is also flexible if you want to add more columns without changing a lot of code, just increase the range of the second loop.

    It could look like this:

    for i in range (1, ws.max_row+1):
        column_list = []
        for j in range (1, 4):
            column_list.append(worksheet.cell(i,j).value)
    
        # the '*' unpacks the whole list
        result = the_class.create(*column_list)
    

    Does that work for you?