pythonfunctionargument-unpackinginterleave

A Python function that interleaves arbitrary number of lists as parameters


Edited for the sake of simplicity, as I have pin pointed the issue to 'argument unpacking'.
I am trying to write a function that interleaves an arbitrary number of lists as parameters. All the lists have equal length. The function should return one list containing all the elements from the input lists interleaved.

def interleave(*args):

    for i, j, k in zip(*args):
        print(f"On {i} it was {j} and the temperature was {k} degrees celsius.")

interleave(["Monday Tuesday Wednesday Thursday Friday Saturday Sunday".split()],["rainy rainy sunny cloudy rainy sunny sunny".split()],[10,12,12,9,9,11,11])

Output:

On ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'] it was ['rainy', 'rainy', 'sunny', 'cloudy', 'rainy', 'sunny', 'sunny'] and the temperature was 10 degrees celsius.

desired output:

On Monday it was rainy and the temperature was 10 degrees celsius.
On Tuesday it was rainy and the temperature was 12 degrees celsius.
On Wednesday it was sunny and the temperature was 12 degrees celsius.
On Thursday it was cloudy and the temperature was 9 degrees celsius.
On Friday it was rainy and the temperature was 9 degrees celsius.
On Saturday it was sunny and the temperature was 11 degrees celsius.
On Sunday it was sunny and the temperature was 11 degrees celsius.

Solution

  • Don't wrap the result of split in a list. So, change

    interleave(["Monday Tuesday Wednesday Thursday Friday Saturday Sunday".split()],["rainy rainy sunny cloudy rainy sunny sunny".split()],[10,12,12,9,9,11,11])

    to

    interleave("Monday Tuesday Wednesday Thursday Friday Saturday Sunday".split(),"rainy rainy sunny cloudy rainy sunny sunny".split(),[10,12,12,9,9,11,11]).

    While the former will result in two lists of length 1 and a list of length 7 as arguments to interleave, the latter/change will result in three lists of length 7 as arguments. The latter is what you need for the zip operator to work as you desire.