Search code examples
pythonpython-3.xfor-looppython-itertools

Iterate over different lists


I'm trying to itterate over 2 different lists in python and after this itteration I want to get new list, which will include new data.

I have a code:

import itertools
current_week = [42,43,44,45,46]
late_pcs = [10,27]
late_week = [45,46]

late_list = []
for week, pcs in itertools.zip_longest(current_week, late_pcs):
    if week not in late_week:
        late_list.extend([0])
    else:
        late_list.extend([pcs])

I need to compare 2 lists. If number from list "current_week" is in "late_week" I need to take number from list "late_pcs".

We're taking number 42 and starting to check if this number is in "late_week". If it's False - we add 0 to "late_list" and so on. If it's True - we add number from "late_pcs".

As a result I need to get new list like this:

late_list = [0, 0, 0, 10, 27]

But I am getting:

[0, 0, 0, None, None]

I know I can use fillvalue for zip_longest, but I don't think that it could be useful for we in this way. Maybe I choiced wrong way to get a right result.


Solution

  • Here is a solution without importing from itertools:

    current_week = [42,43,44,45,46]
    late_pcs = [10,27]
    late_week = [45,46]
    
    late_list = []
    for week in current_week:
        if week in late_week:
            late_list.append(late_pcs.pop(0))
        else:
            late_list.append(0)
    
    print(late_list)