0

I have 2 list's in the following form:

  list1 = [["abc",45,48],["def",13,16]]
  list2 = [["efgh",67,71],["def",13,16]]

How can I find the union of these 2 lists?

Required output:

  union_list = [["abc",45,48],["def",13,16],["efgh",67,71]]

If this helps: As you can see, the list[0][1] and list[0][2] are integers, we can typecast it to a string if necessary.

Vasu Mistry
  • 781
  • 2
  • 6
  • 18
  • 1
    Possible duplicate of [Pythonic Way to Create Union of All Values Contained in Multiple Lists](http://stackoverflow.com/questions/2151517/pythonic-way-to-create-union-of-all-values-contained-in-multiple-lists) – Andrew Li Jan 01 '17 at 05:07

3 Answers3

2

You can use set.union, i.e, you can map both lists to list of tuples and then convert them to sets so that you can call the union method:

u_set = set(map(tuple, list1)).union(map(tuple, list2))

# {('abc', 45, 48), ('def', 13, 16), ('efgh', 67, 71)}

To convert them back to lists:

list(map(list, u_set))
# [['def', 13, 16], ['efgh', 67, 71], ['abc', 45, 48]]
Psidom
  • 209,562
  • 33
  • 339
  • 356
1

You can use a set comprehension. Since list are un-hashable however, tuple()'s must be used instead.

>>> list1 = [["abc",45,48],["def",13,16]]
>>> list2 = [["efgh",67,71],["def",13,16]]
>>> {tuple(sublist) for sublist in list1 + list2}
set([('def', 13, 16), ('efgh', 67, 71), ('abc', 45, 48)])
>>> 
Christian Dean
  • 22,138
  • 7
  • 54
  • 87
1

You can use

[list(x) for x in unique_everseen(tuple(y) for y in chain(list1, list2))]

unique_everseen() can be found in the documentation of module itertools. Conversion to tuple is necessary because the list type is not hashable.

Gribouillis
  • 2,230
  • 1
  • 9
  • 14
  • `chain()` is _also_ found in the `itertools` library. It is usually a good idea to show the functions you import rather than just using them. Also, a link to the documentation of each function wouldn't hurt. – Christian Dean Jan 01 '17 at 05:25
  • @leaf I added a link to itertools documentation. Notice that unique_everseen is not included in itertools, it is documented as a (useful) recipe. – Gribouillis Jan 01 '17 at 05:29