In your case you should probably just check if the index is longer than the sequence:
list1 = [1, 2, -3, 4, 7]
list2 = [4, -6, 3, -1]
final_list = []
for index in range(max(len(list1), len(list2))):
if index < len(list1):
if list1[index] < 0:
final_list.insert(0, list1[index])
elif list1[index] > 0:
final_list.insert(len(final_list), list1[index])
if index < len(list2):
if list2[index] < 0:
final_list.insert(0, list2[index])
elif list2[index] > 0:
final_list.insert(len(final_list), list2[index])
print(final_list)
# [-1, -3, -6, 1, 4, 2, 3, 4, 7]
Or use itertools.zip_longest
(or itertools.izip_longest
on python-2.x) and check for some fillvalue (i.e. None
):
import itertools
list1 = [1, 2, -3, 4, 7]
list2 = [4, -6, 3, -1]
final_list = []
for item1, item2 in itertools.zip_longest(list1, list2, fillvalue=None):
if item1 is None:
pass
elif item1 < 0:
final_list.insert(0, item1)
elif item1 > 0:
final_list.append(item1)
if item2 is None:
pass
elif item2 < 0:
final_list.insert(0, item2)
elif item2 > 0:
final_list.append(item2)
However your approach skips items when they are == 0
, that's probably an oversight but you should check that it's working correct with zeros.
Also you use insert
a lot. The last elif
s could instead use final_list.append(item1)
(or item2
), like I did in the second example.
In this case the handling for item1
and item2
is identical, so you could use another loop:
import itertools
list1 = [1, 2, -3, 4, 7]
list2 = [4, -6, 3, -1]
final_list = []
for items in itertools.zip_longest(list1, list2, fillvalue=None):
for item in items:
if item is None:
pass
elif item < 0:
final_list.insert(0, item)
elif item > 0:
final_list.append(item)