0

I have a huge list of lists. I want to Merge all child lists to parent list and remove duplicates item from parent list after merge.

What is the optimized way to do this?

For Example:

x = [['a', 'b', 'c', 2, 4], ['x', 1, 2, 3, 'z'], ['z', 'b', 'y', 'a' 'x']]

How we can get the value of x like:

['a', 'b', 'c', 1, 2, 3, 4, 'z', 'y', 'x']

Rajiv Sharma
  • 6,746
  • 1
  • 52
  • 54

3 Answers3

4

Use set and chain:

x = [['a', 'b', 'c', 2, 4], ['x', 1, 2, 3, 'z'], ['z', 'b', 'y', 'a' 'x']]

from itertools import chain

result = list(set(chain.from_iterable(x)))
print(result)
Menglong Li
  • 2,177
  • 14
  • 19
4

Use set

x = [['a', 'b', 'c', 2, 4], ['x', 1, 2, 3, 'z'], ['z', 'b', 'y', 'a' 'x']]
>>> list(set([item for sublist in x for item in sublist]))
[1, 2, 3, 4, 'z', 'ax', 'a', 'b', 'c', 'x', 'y']
Ma0
  • 15,057
  • 4
  • 35
  • 65
akash karothiya
  • 5,736
  • 1
  • 19
  • 29
2

first you can convert the list of list into a one list and than apply set to that list.

x = [['a', 'b', 'c', 2, 4], ['x', 1, 2, 3, 'z'], ['z', 'b', 'y', 'a' 'x']]
new_ls=[]
for ls in x:
    new_ls.extend(ls)
print(list(set(new_ls))

output:

[1, 2, 3, 4, 'ax', 'b', 'y', 'x', 'c', 'z', 'a']
R.A.Munna
  • 1,699
  • 1
  • 15
  • 29