Loop throw two lists, and I want to pop from each one

Viewed 44

I have two lists:

revenue_list_per_day = [3.750525, 3.751132, 3.750959, 3.750447]

day_list = [datetime.date(2021, 4, 20), datetime.date(2021, 4, 21), datetime.date(2021, 4, 22), datetime.date(2021, 4, 23)]

for i in revenue_list_per_day: 
    revenue_list_per_day.pop(0)   
    for n in day_list:
        day_list.pop(0)
        print(i,n)  

OUTPUT =>

3.750525 2021-04-20

3.750525 2021-04-22

3.750959 2021-04-22

EXPECTED =>

3.750525 2021-04-20

3.751132 2021-04-21

3.750959 2021-04-22

3.750447 2021-04-23

What do you think I should do?

1 Answers

You can simply use the zip() built-in function :

for revenue, date in zip(revenue_list_per_day, day_list):
    print(revenue, date)

And that's all ! But if you like a long way, here is one:

for i in range(len(revenue_list_per_day)):
    print(revenue_list_per_day[i], day_list[i])

This does the same thing though it has a drawback which is if the two lists (revenue_list_per_day and day_list) aren't of the same length, the terminal will throw an error.

However, with the zip() function, it won't because :

The iterator stops when the shortest input iterable is exhausted.

as the documentation says.

Related