wrosen01
wrosen01

Reputation: 127

Iterate increasing values in two lists

I have two lists:

a = [0, 3, 5, 6, 10, 14]
b = [2, 4, 8, 9, 12, 17]

I would like to iterate over both at the same time in alternating steps and deal with the values in increasing order. So if we were printing each value they would be in this order:

0, 2, 3, 4, 5, 6, 8, 9, 10, 12, 14, 17

I've messed around with it, trying things like:

i = 0
j = 0
while i < len(a) or j < len(b):
    if a[i] < b[j]:
        print a[i]
        i += 1
    elif b[j] < a[i]:
        print b[j]
        j += 1

but this results in a keyerror at the end of one of the lists.

Upvotes: 4

Views: 54

Answers (4)

wjandrea
wjandrea

Reputation: 33107

As Andrej commented, you can use heapq.merge instead:

>>> import heapq
>>> print(*heapq.merge(a, b))
0 2 3 4 5 6 8 9 10 12 14 17

Upvotes: 0

wjandrea
wjandrea

Reputation: 33107

You just need to use and instead of or and afterwards print whatever's remaining:

while i < len(a) and j < len(b):
    ...
k, remaining = (i, a) if i < len(a) else (j, b)
for x in remaining[k:]:
    print(x)

Upvotes: 0

MarianD
MarianD

Reputation: 14181

Combine them and then sort the result:

c = sorted(a + b)

Upvotes: 2

Kenan
Kenan

Reputation: 14104

I think zip is what you want

for aa ,bb in zip(a, b):
    print(f'{aa},{bb}')

Upvotes: 0

Related Questions