Reputation: 460
I'm relatively new to python and programming, I am trying to solve a problem which requires to print out the pair of numbers where the difference of both numbers == 2. Here's my attempt:
l = [1, 2, 3, 5, 7, 11, 13, 17, 19, 23]
k = []
count = 0
a = l[0] #initialize a to be the element in the first index
#b = l[1]
while (count < len(l)): #while count is less than length of list
for i in range(len(l)): #for each element i in l,
k.append(a) #append it to a new list k
a, b = l[i+1], l[i+1] #Now a and b pointers move to the right by 1 unit
count += 1 #update the count
print(k[i]) #print newly updated list k
if(a - b == 2): #attempting to get the difference of 2 from a,b. if difference a,b == 2, append them both
#If fail, move on to check the next 2 elements.
#k.append(l[i])
print(k)
The code gets stuck at a,b = l[i+1],l[i+1]
. To help you visualize what's going on with the code, refer to: http://goo.gl/3As1bD
Appreciate any help! Sorry if it's abit messy. All I want to do is to be able to traverse each element in the list while comparing their differences if it's == 2
Thanks! Looking forward to alternatives
Upvotes: 0
Views: 57
Reputation: 107337
The problem is that you are iterating over range(len(l))
and tried to get the front item by l[i+1]
which makes you get an IndexError
:
For example :
>>> l = [1,2,3]
>>>
>>> l[len(l)+1]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
For get ride of this problem you should loop over range(len(l)-1)
and for first item use l[i]
:
for i in range(len(l)-1): #for each element i in l,
k.append(a) #append it to a new list k
a, b = l[i], l[i+1]
Upvotes: 2
Reputation: 59661
Why not do a double nested for loop:
l = [1, 2, 3, 5, 7, 11, 13, 17, 19, 23]
for i in l:
for j in l:
if abs(i-j) == 2:
print(i, j)
Upvotes: 0
Reputation: 67978
You can simply do
l = [1, 2, 3, 5, 7, 11, 13, 17, 19, 23]
[(i,j) for i,j in zip(l,l[1:]) if abs(i-j)==2]
Output:[(3, 5), (5, 7), (11, 13), (17, 19)]
Upvotes: 2