0

I want to be able to shortened the if statement if possible. I want to be able to add the tuple only if the tuple is not already in the list, despite the order. I am checking if the item is in the list but at every index, which is kind of inefficient when the tuple would be more than 2 items.

complete_list = [(1,2), (1, 3), (4,1), (3,2)]

# Item (2,1) wouldn't be added, Item (1,2) is in the list
# Item (4,3) would be added, Item (3,4) is not in the list

if (item1.id, item2.id) not in complete_list and (item2.id, item1.id) not in complete_list :
    complete_list.append((item1.id, item2.id))

Item1.id is not always lower than Item2.id and I want to keep item1 as the first element of my tuple. I would have probably sorted the tuple before appending it (and checking if it is in the list).

Abhyuday Vaish
  • 2,272
  • 5
  • 9
  • 24

0 Answers0