0

I have a 2d list of 2 elements in each row and I want to concatenate two rows with a common element and append it to another list but do not want the common element to be repeated. Here is something similar to what I tried

list1 = [['apple','orange'],['apple','banana'],['banana','mango'],['orange','mango']
list2 = []
for i in range(len(list1)-1):
    for j in range(i+1,len(list1)):
      if list1[i][0] in list1[j]:
        if list1[i][1] + list1[j] not in list2:
          list2.append(list1[i][1] + list1[j])
      elif list1[i][1] in list1[j]:
        if list1[i][0] + list1[j] not in list2:
          list2.append(list1[i][0] + list1[j])
print(list2)

but this gives me an error saying "can only concatenate str (not "list") to str" and if I just use "+" to concatenate both lists then common element is added twice. Expected result is

[['apple','orange','banana'],['apple','orange','mango'],['apple','banana','mango'],['banana','mango','orange']]

Surely there must be an easier way to concatenate while excluding common elements.

1 Answers1

0

If I understood you correctly:

list1 = [['apple','orange'],['apple','banana'],['banana','mango'],['orange','mango']]
list2 = []

for pair in list1:
   list2.extend(pair)

# Using list(set()) removes duplicates
list2 = list(set(list2))

print(list2)

Another way of unpacking list1:

list1 = [['apple','orange'],['apple','banana'],['banana','mango'],['orange','mango']]
list2 = []

def flatten(l):
    return [item for sublist in l for item in sublist]

# Using list(set()) removes duplicates
list2 = list(set(flatten(list1)+list2))

print(list2)

Comment below if it does not answer your question


Useful links:

Aleksei
  • 77
  • 8
  • extend does not remove duplicate elements as well, so what I want from this code is ['apple','orange','banana','mango'], but it gives ['apple','orange','apple','banana','banana','mango','orange','mango'] – aditya singh Aug 01 '22 at 22:08
  • @adityasingh I forgot a keyword. I will insert the correction right now. But also will look for a more optimal way to do what you want. – Aleksei Aug 02 '22 at 09:04