-3

I was wondering how to choose the different elements of two different lists using loops.

Let's say I have 2 lists: a = ['apple', 'cherry','banana', 'pineapple', 'cheese'] b =['apple', 'pear', 'watermelon', 'banana'] '

and I want the result ['cherry', 'pear', 'pineapple', 'watermelon', 'cheese']

  • 1
    Does this answer your question? [Python sets: difference() vs symmetric\_difference()](https://stackoverflow.com/questions/50871370/python-sets-difference-vs-symmetric-difference) – Abhyuday Vaish Apr 11 '22 at 14:28

2 Answers2

1

Using sets (with built-in level optimization):

set_a = set(a)
set_b = set(b)
new_list = list((set_a - set_b) + (set_b - set_a))
print(new_list)
  • `list(set_a ^ set_b)` is equivalent, and since it contains no repeats of variable names, also less error prone – hintze Apr 11 '22 at 14:50
-1

If you want to use only lists you can use this solution with double for loop. Each for loop check one list and take one element only on time which it put to a new list. And after we print the new list.

#lists
a = ['apple', 'cherry','banana', 'pineapple', 'cheese']

b =['apple', 'pear', 'watermelon', 'banana']

#create empty list

c=[ ] 

#put all elements of a not in b to c

for i in a:

    if i not in b and i not in c:

        c.append(i)

#put all elements of b not in a to c

for i in b:

    if i not in a and i not in c:

        c.append(i)

#print c
print(c)
TechM25
  • 1
  • 2
  • using list this is the solution what OP want, but this is not good as it is O(N*N), you can change a and b into set or dictionary so that search is O(1) not O(N) every time. plus this solution fail when there are multiple commone element in a single list and not in other, for example 'cheery' occur 3 time in list `a` and with your code will be added 3 times, which is not desired – sahasrara62 Apr 11 '22 at 14:50
  • 1
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Apr 11 '22 at 16:13