0

This compares the values in both lists for common numbers.

 a = [1, 2, 2, ]
 b = [1, 2, 3, 3, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 12]
 c = a + b
 new = []

 for i in c:
    if i not in new:
        new.append(i)

 print(new)

Why is new = [] necessary? Is there no way to figure this out with just c?

Selcuk
  • 57,004
  • 12
  • 102
  • 110

2 Answers2

3

Assuming all your values are hashable (int is), you can avoid the explicit loop by converting to an ordered dictionary type (to dedupe), then back to list:

from collections import OrderedDict

a = [1, 2, 2, ]
b = [1, 2, 3, 3, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 12]
new = list(OrderedDict.fromkeys(a + b))
print(new)

On modern Python (CPython/PyPy 3.6 as an implementation detail, any interpreter on 3.7+ as a language guarantee), dict itself is insertion ordered, so no import is necessary, and the definition of new can shorten to:

new = list(dict.fromkeys(a + b))
ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
0

Do you mean like this one:

a = [1, 2, 2]
b = [1, 2, 3, 3, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 12]
c = a + b
list(set(c))

Output:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
YusufUMS
  • 1,506
  • 1
  • 12
  • 24
  • 1
    Note that using `set` here loses order. – Christian Dean Mar 13 '19 at 03:06
  • Interesting. I was not aware of the set() function. Are there any advantages of using the for function rather than set? – AnacondianPython Mar 13 '19 at 03:07
  • Yes, that's the drawback of using `set()`. – YusufUMS Mar 13 '19 at 03:07
  • 1
    @AnacondianPython: The advantage of `set` (and my `dict` based solution as well) is that they're `O(1)` to perform insertion and membership testing, and naturally unique. `list`s are `O(n)` for membership testing (amortized `O(1)` for insertion at the end at least), so the loop you used is `O(n**2)` (`n` for outer loop, times `n` for each membership test), where a `set` or `dict` based solution is only `O(n)` (`n` to loop over input, but membership test/insertion remains `1` work). Going from 100 input items to 1000 input items would increase work 10x for `set`/`dict`, or 100x for your `list`. – ShadowRanger Mar 13 '19 at 03:17