Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if two variables are in the same list

What would be the best way to ensure that two different variables are in the same list before doing something with them? For example:

var1 = 1
var2 = 2
var3 = 3
var4 = 4
list1 = [var1, var2, var3, var4]
var5 = 5
var6 = 6
var7 = 7
var8 = 8
list2 = [var5, var6, var7, var8]

if var1 and var2 (are in the same list):
    print("In the same list")
else: 
    print("Not the same")

Would it be better to use a tuple or something else instead of lists, which would make this easier?

like image 347
John Smith Avatar asked Mar 22 '23 12:03

John Smith


1 Answers

>>> list1 = list(range(1, 5))
>>> 1 in list1 and 2 in list1
True
>>> 1 in list1 and 6 in list1
False

If you're checking multiple items, then go for all:

>>> to_be_checked = [1, 2, 3, 4]
>>> all(item in list1 for item in to_be_checked)
True

Don't create separate variables for each item, just put them in the list from the start.


For efficieny use sets, sets provide O(1) loopkup. Note that sets don't have any order and you can't do indexing on them

>>> list1 = list(range(10**5))
>>> s = set(range(10**5))
>>> %timeit 1000 in list1 and 10**5 in list1
100 loops, best of 3: 2.71 ms per loop
>>> %timeit 1000 in s and 10**5 in s
1000000 loops, best of 3: 403 ns per loop
like image 67
Ashwini Chaudhary Avatar answered Mar 31 '23 14:03

Ashwini Chaudhary