0

Suppose we have

 temp1 = [1, 2, 3]
 temp2 = [1, 2, 3]
 temp3 = [3, 4, 5]

How do I get the union of the three temporary variables?

Expected result: [[1,2,3],[3,4,5]].

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
shivram
  • 469
  • 2
  • 10
  • 26

2 Answers2

2

You can use the built-in set to get unique values, but in order to reach this with list objects you need first to transform them in hashable (immutable) objects. An option is tuple:

>>> temp1 = [1,2,3]
>>> temp2 = [1,2,3]
>>> temp3 = [3,4,5]
>>> my_lists = [temp1, temp2, temp3]

>>> unique_values = set(map(tuple, my_lists))
>>> unique_values  # a set of tuples
{(1, 2, 3), (4, 5, 6)}

>>> unique_lists = list(map(list, unique_values))
>>> unique_lists  # a list of lists again
[[4, 5, 6], [1, 2, 3]]
leogama
  • 898
  • 9
  • 13
1

I created a matrix to change the code easily for a generalized input:

temp1=[1,2,3]
temp2=[3,2,6]
temp3=[1,2,3]
matrix = [temp1, temp2, temp3]

result = []
for l in matrix:
    if l not in result:
        result.append(l)

print result
ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199