ah2Bwise
ah2Bwise

Reputation: 142

A For loop that has multiple iterators and refers to list index

I want to iterate over three lists, but the number of iterations should only be range(len(dfs)).

Where I am having trouble is figuring out the best way to structure this so that it has both a range for the number of iterations, and has multiple iterators.

dfs = [df1, df2]
sheet_tabs = ['abc', 'def']
years = [2020, 2021]


for df[x], tab[x], year[x] in zip(dfs, sheet_tabs, years):
    if not df[x].empty:
        df[x] = ...

what I am kind of after but think there is a better approach...:

for df[x], tab[x], year[x] in range(len(zip(dfs, sheet_tabs, years))):

The reason for using indexes is because of this question I asked: Iterating over lists produces unexpected results

Upvotes: 0

Views: 56

Answers (1)

grbeazley
grbeazley

Reputation: 198

You can use enumerate on any iterator to get an increasing number sequence, for your example:

for idx, (df, tab, year) in enumerate(zip(dfs, sheet_tabs, years)):
    # Do work
    # For immutable objects, e.g. strings or ints:
    sheet_tabs[idx] = 'foo'

    # For mutable objects, you can update them directly
    df['c'] = df['a'] + df['b']

This is because enumerate returns two items, the index idx, and the next value from the sequence. In this case the next sequence value is a tuple from the zip statement so we unpack it to the three elements in the same step.

See enumerate docs: https://docs.python.org/3/library/functions.html#enumerate

Upvotes: 1

Related Questions