Iterate over two lists with different lengths

Viewed 24438

I have 2 lists of numbers that can be different lengths, for example:

list1 = [1, 2, -3, 4, 7]
list2 = [4, -6, 3, -1]

I need to iterate over these with the function:

final_list = []
for index in range(???):
    if list1[index] < 0:
        final_list.insert(0, list1[index])
    elif list1[index] > 0:
        final_list.insert(len(final_list), list1[index])
    if list2[index] < 0:
        final_list.insert(0, list2[index])
    elif list2[index] > 0:
        final_list.insert(len(final_list), list2[index])
return final_list

but can't figure out how to deal with the range as the shorter list will become "out of range" if I use the max length. Any thoughts on how to overcome this or how to change my function?

3 Answers
Related