Search code examples
pythonvariablesmembershipiterable-unpacking

Can I unpack variables in order to check their membership in another list?


I would like to know if I have a list of integers, then can I unpack them to check if they are present in another list or must I do it manually? I know there are built in functions like any() and all() but I am wondering if we can unpack variables during a membership test.

list1 = [1,2,3,4,5,6,7,8,9,0]
list2 = [5,3,2,]
if (*list1) in list2:
    print("it works")

Solution

  • A function that needs arguments from a collection data type accepts unpacking of the collection. You can check membership in this function by comparing the unpacked args against items in another collection. Below is a custom function that accepts unpacking of list1 and compares items in this list against another list list2.

    list1 = [1,2,3,4,5,6,7,8,9,0]
    list2 = [5,3,2]
    
    def intersection(*args, list2):
        for i in args:
            if i in list2:
                print(i)
    
    intersection(*list1, list2=list2)
    #Output:
    2
    3
    5
    

    You can also use built-in set operations like intersection to achieve similar results:

    set(list1).intersection(list2)
    #Ouptut:
    {2, 3, 5}