Assuming that the goal is to just iterate elements of both collections (and not to produce and iterate some kind of Cartesian product) and if we are talking Big-O notation then from algorithmic point of view it does not matter - both will require O(m+n) (where m and n are length of list_a
and list_b
respectively) operations. The actual speed will be implementation specific, for example if you do something like list_a.extend(list_b)
and then will iterate - then it will be slower due to the need to move elements (for simplicity we can consider it to be O(n)) but if you will be using some lazy iterable approach (for example itertools.chain
as mentioned by @Jorge Luis) then the speed should be comparable.
In some cases you can "reduce" the Big-O to O(max(m, n)) by iterating them in one cycle for min(m, n) elements and then finishing the longer one in separate loop (pseudocode to get the idea):
longest = list_a if len(list_a) > len(list_b) else list_b
for i in range(min(len(list_a), len(list_b))):
print(list_a[i])
print(list_b[i])
for j in range(i+1, max(len(list_a), len(list_b))):
print(longest[j])
Which is similar to what itertools.zip_longest
does (as correctly mentioned by @chepner)