0

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

2
  • for df[x], tab[x], year[x] what's with the indexes? Why doesn't the regular (and syntactically correct) way work?
    – CristiFati
    Commented Apr 12, 2022 at 14:59
  • I just updated this with a link to a similar question I asked
    – ah2Bwise
    Commented Apr 12, 2022 at 15:01

1 Answer 1

1

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.