Search code examples
pythonlistenumerate

Python how to skip the first (i.e. zero) iteration using enumerate and a list?


I have a table object.

I want to check to see if the first row has the value of Test, in which case I need to do something with each row in the table.

Otherwise, if the first row does not have the value of Test I need to skip that row and do something with rows 1 and on.

Because I need both the index and the row, I have to use enumerate, but it seems like I am using it in a messy way. Here I am calling enumerate twice and checking to see if the index is 0 twice. Is there a more concise way to to this?

for i, r in enumerate(null_clipData.rows()):
    if r[0].val == 'Test':
        # Do something if the first row is Test
        for index, row in enumerate(null_clipData.rows()):
            if index == 0:
                continue # But do anything the first time (stay in this loop though)
            print(index, row)
        break # All through with test row

    if i == 0:
        continue # Don't do anything with the first row if the value was not Test

    print(i, r) # Do something with i and r

Solution

  • Following Kevin’s advice, you can handle the first item separately, and then continue with the loop:

    rows = iter(null_clipData.rows())
    
    firstRow = next(rows)
    specialHandling = firstRow.val == 'Test'
    
    for i, r in enumerate(rows, start=1):
        if specialHandling:
            # do something special with r
        else:
            # do the normal stuff with r
    

    Alternatively, you can also keep it in a single loop:

    specialHandling = False # default case
    for i, r in enumerate(null_clipData.rows()):
        if i == 0: # first item
            specialHandling = r == 'Test'
            continue
    
        if specialHandling:
            # do something special with r
        else:
            # do the normal stuff with r