Loop over a list and compare an item in a list to other two simultaneously

Viewed 308

This itertools example compares only 1 item to another. I need to compare 1 item to 2 others at the same time.

my_list = [10, 420, 11]

I need to be able to compare these items in the query below, with the following comparisons:

  • 10 to both 420 and 11 (as in the code below),
  • 420 to both 10 and 11,
  • 11 to both 420 and 10.

I'm running this inside of a SQL query.

SELECT COUNT(*) FROM (
   SELECT app FROM vendor WHERE vendor=10 AND active
   INTERSECT
   SELECT app FROM vendor WHERE vendor NOT IN (420, 11) AND active = 0
   )
2 Answers

This will compare all possible combinations of elements from your list.

arr = [10, 420, 11]

for i, el in enumerate(arr):
    leftover = arr[:i] + arr[i+1:]
    print(el, leftover, el in leftover)

prints the following:

10 [420, 11] False
420 [10, 11] False
11 [10, 420] False

Write a function that returns a copy of a list with a specified element removed. Then iterate over the list, returning each item and the list with that item removed.

def list_without(l, i):
    result = l[:] # copy list
    l.pop(i) # remove the specified index
    return l

my_list = [10, 420, 11]

my_combinations = [(item, list_without(my_list, i)) for i, item in enumerate(my_list)]
print(my_combinations)
# output:
# [(10, (420, 11)), (420, (10, 11)), (11, (10, 420))]
Related