Why is my for loop skipping an element in my list?
What you are trying to do will not work, as you are modifying the list while you are iterating it. Say the current "pointer" points to the first element. Now you pop the first, so the pointer is at the second. But when the loop advances, the pointer is moved to the third, and the second is skipped.
It seems you want to find combinations from a list. There are a few other ways you can try:
Closest to your current approach: Use a
while
loop instead offor
loopwhile l: first = l.pop(0) for second in l: print(first, second)
Or you could just iterate the indices instead of the lists themselves:
for i in range(len(l)): for k in range(i+1, len(l)): print(l[i], l[k])
Or just use
itertools.combinations
import itertools for first, second in itertools.combinations(l, 2): print(first, second)
However, you can do better than that. Since you are looking for a pair of numbers that adds up to some target number, just subtract the first from the target to get the second and see if that second number is in the list of numbers. Use a set
to make this lookup happen in constant time, reducing your overall time complexity from O(n²) to O(n).
numbers = set([1,2,5,8,13,15,26,38])
target = 10
for first in numbers:
second = target - first
if second > first and second in numbers:
print(first, second)