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?
itertools.zip_longest(*iterables, fillvalue=None)
will do the job for you:For your example lists, this will yield:
If you only want to use as many values as are present in both lists, use the built-in
zip()
:In your case you should probably just check if the index is longer than the sequence:
Or use
itertools.zip_longest
(oritertools.izip_longest
on python-2.x) and check for some fillvalue (i.e.None
):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 lastelif
s could instead usefinal_list.append(item1)
(oritem2
), like I did in the second example.In this case the handling for
item1
anditem2
is identical, so you could use another loop:You can process adjacent items from the lists by using
itertools.zip_longest()
(itertools.izip_longest()
if using Python 2) to produce a sequence of paired items. Pairs will be padded withNone
for lists of mismatched length.Then you can simplify the code in the body of the loop by flattening the sequence of paired items and filtering out the
None
values, and in your case,0
values. That's what the generator expression below does.Then it's just a matter of appending or inserting values into
final_list
if greater or less than zero respectively.In code:
Notice that this will filter out any zero values that might be present in the lists. If you want to keep these then modify the generator expression to filter out the
None
values only:and modify the body of the loop to insert the
0
wherever it should go infinal_list
.