-3

So I have two list. For example:

list1 = [a1, b2, c3, f6]
list2 = [a1, b2, d4, e5]

And I want only values that uniquely appear within list2 to append to a new list. For example:

list3 = [d4, e5]
B.John
  • 7
  • 2
  • There is no `if loop` and your code is so far off that I think you should work through the [Python Tutorial](https://docs.python.org/3/tutorial/) first instead of playing whack-a-mole with names and comparison operators. – timgeb Oct 16 '18 at 12:20

2 Answers2

2

You could use a list comprehension.

list3 = [item for item in list2 if item not in list1]

Output

list3 = ['d4', 'e5']
Mihai Alexandru-Ionut
  • 47,092
  • 13
  • 101
  • 128
  • Yes, but OP does not even know how to write a `for` loop, or how to use `list.append` or comparison operators properly. They will copy-paste your code and never learn them. – timgeb Oct 16 '18 at 12:21
0

You can convert list1 to a set first so you can efficiently test if an item in list2 is in the set while you iterate over list2:

list1 = ['a1', 'b2', 'c3', 'f6']
list2 = ['a1', 'b2', 'd4', 'e5']
set1 = set(list1)
list3 = [i for i in list2 if i not in set1]

list3 would become:

['d4', 'e5']
blhsing
  • 91,368
  • 6
  • 71
  • 106