Your pseudo code will almost work in Python. Some working code that does what you want is:
a = [1, 3, 5, 7]
b = [2, 4, 9]
j = 0
for i in range(len(a)):
print a[i], b[j]
while j<len(b)-1 and b[j+1] <= a[i]:
j += 1
print a[i], b[j]
Note the few changes to make it work in Python:
- When declaring the list, commas are required between items.
- List indices start at 0, so both
i and j should start there.
len(a) returns the length of a (4 in this case), and iterating i through range(len(a)) executes the loop for each integer from 0 to len(a)-1, which is all of the indices in a.
- The
++ operation is not supported in Python, so we use j +=1 instead.
- We have to avoid using out of bounds indices of
b, so we test to make sure j will be in bounds before incrementing it.
This code can be made more pythonic by iterating through the list as follows:
a = [1, 3, 5, 7]
b = [2, 4, 9]
j = 0
for element in a:
print element, b[j]
while j<len(b)-1 and b[j+1] <= element:
j += 1
print element, b[j]
In general, you probably don't want to just print list elements, so for a more general use case you can create a generator, like:
def sync_lists(a, b)
if b:
j = 0
for element in a:
yield (element, b[j])
while j<len(b)-1 and b[j+1] <= element:
j += 1
yield (element, b[j])
And then you can print them as before with
a = [1, 3, 5, 7]
b = [2, 4, 9]
for (e1, e2) in sync_lists(a, b):
print e1, e2