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]
From the docs: https://docs.python.org/3/library/stdtypes.html#frozenset.union
Also
*listis called list unpacking, where we get the two sublists inside the listSo 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 doinga.union(b),aandbbeing setsAdding to this, a better approach to do
unionor evenintersectionmight be to convert the list of lists to a list of sets, usingmap(set,list1), unrolling the sets and then doing the operations