-1

Given the following code

list_a = ['Zara', 'Nike', 'Addidas', 'Uniqlo']
list_b = ['Nike', 'Addidas']
result = []
for brand in list_a:
    for brand_two in list_b:
        if brand_two != brand:
            result.append(brand)
print(result)

Issue

I am trying to get elements that are only present in either list_a or list_b not both. I am getting the following output right now.['Zara', 'Zara', 'Nike', 'Addidas', 'Uniqlo', 'Uniqlo'] but i am expecting only ['Zara', 'Uniqlo']

Sluna
  • 169
  • 10
  • the question is closed, make sure to read well the documentation of `set` before using it. Before the difference of `set(A) - set(B)` is not the same as `set(B) - set(A)` – ombk Nov 28 '20 at 18:05
  • It is important to understand why your code is giving you that output. When you are iterating through your lists, you check if the first and second elements in list_b are not in list_a. If they are not, you append the first element of list_a to a new list twice. You repeat this loop with Nike, Adidas and Uniqalo. You append Zara because it is not in Nike and you append it again because it is not in Adidas. Same goes for Uniqalo. Do you understand what you are making python do? – DarknessPlusPlus Nov 28 '20 at 18:13
  • From the docs for `set` *Return a new set with elements in either the set or other but not both.* `set(list_a).symmetric_difference(set(list_b))` – Chris Charley Nov 28 '20 at 18:55

2 Answers2

0

You could use a set:

list_a = ['Zara', 'Nike', 'Addidas', 'Uniqlo']
list_b = ['Nike', 'Addidas']

print(set(list_a).difference(list_b))

Out:

{'Zara', 'Uniqlo'}
ombk
  • 2,036
  • 1
  • 4
  • 16
Maurice Meyer
  • 17,279
  • 4
  • 30
  • 47
0
list_a = ['Zara', 'Nike', 'Addidas', 'Uniqlo']
list_b = ['Nike', 'Addidas']
result = []

for brand in list_a:
    if brand not in list_b:
        result.append(brand)
print(result)

You just need to check if brand from list_a is not in list_b and append answer questions accordingly.

Another approach is to use a set as follows

list_a = ['Zara', 'Nike', 'Addidas', 'Uniqlo']
list_b = ['Nike', 'Addidas']
result = list(set(list_a) - set(list_b))
print(result)
gosalia
  • 182
  • 9