# How to compare items in list?

## Question:

This is my list

``````my_list = [18, 19, 20, 27, 28, 29, 38, 39, 40]
``````

My goal is to sort or create new lists like these

``````list1 = [18, 19, 20]
list2 = [27, 28, 29]
list3 = [38, 39, 40]
``````

And then compare each of them and only leave items which are equal like that ,

``````list1 x == list2 x - 10 or list1 x == list3 x - 10
list1 x == list2 x + 10 or list1 x == list3 x + 10
list2 x == list1 x - 10 or list2 x == list3 x - 10
list2 x == list1 x + 10 or list2 x == list2 x + 10
list3 x == list1 x - 10 or list3 x == list2 x - 10
list3 x == list1 x + 10 or list3 x == list2 x + 10
``````

So the final list will be like

``````final = [18,19,28,29,38,39]
``````

I have wrote those codes but can’t achieve the goal. Those were just unsuccessful attempts.

N1

``````for lst in my_list:
ind = my_list.index(lst)
if int(my_list[ind]) == any(int(x)-10 for x in my_list) or int(my_list[ind]) == any(int(x)+10 for x in my_list):
print(ind)
``````

N2

``````for id in my_list:
ind = my_list.index(id)
try:
if id == (my_list[ind+1])-1 and id :
print(id)
except IndexError:
print("out of", id)
``````

Thank you in advance.

It sounds like you want to take a list as input and generate a new list that only contains elements of the original that are 10 away from another element in the original.

``````my_list = [18, 19, 20, 27, 28, 29, 38, 39, 40]
new_list = list(filter(lambda x: x + 10 in my_list or x - 10 in my_list, my_list))
``````

Here is a simple way to do just that using python’s `filter` method.

Results:

``````[18, 19, 28, 29, 38, 39]
``````
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.