Search code examples
pythonpython-3.xsetargument-unpackingset-union

Why does set().union(*list1) gives me the union of two list inside a list?


I am doing an assignment, which requires me to do a code walkthrough. I would like to have a brief description on how set().union(*list1) works so i can answer during my walkthrough.

list1 = [[1,2,3],[1,2,3,5,8]]

x = set().union(*list1)

print(list(x))



#output = [1, 2, 3, 5, 8]

Solution

  • From the docs: https://docs.python.org/3/library/stdtypes.html#frozenset.union

    union(*others)
    set | other | ...
    Return a new set with elements from the set and all others.

    Also *list is called list unpacking, where we get the two sublists inside the list

    In [37]: list1 = [[1,2,3],[1,2,3,5,8]]                                                                                         
    
    In [38]: print(*list1)                                                                                                         
    [1, 2, 3] [1, 2, 3, 5, 8]
    

    So the code you ran essentially creates a union of all the sublists within the list x, and since you know that the union of set [1,2,3] and [1,2,3,5,8] is [1,2,3,5,8], hence the expected result.

    Note that this is equivalent to list(set([1,2,3]).union(set([1,2,3,5,8]))) where we are doing a.union(b), a and b being sets

    In [31]: list1 = [[1,2,3],[1,2,3,5,8]] 
        ...:  
        ...: x = set().union(*list1)                                                                                               
    
    In [32]: print(list(x))                                                                                                        
    [1, 2, 3, 5, 8]
    
    In [33]: print(list(set([1,2,3]).union(set([1,2,3,5,8]))))                                                                     
    [1, 2, 3, 5, 8]
    

    Adding to this, a better approach to do union or even intersection might be to convert the list of lists to a list of sets, using map(set,list1), unrolling the sets and then doing the operations

    In [39]: list1 = [[1,2,3],[1,2,3,5,8]]                                                                                         
    
    In [40]: print(set.intersection(*map(set,list1)))                                                                              
    {1, 2, 3}
    
    In [41]: print(set.union(*map(set,list1)))                                                                                     
    {1, 2, 3, 5, 8}