Your teacher's approach is better than yours, the main reason is the one noted in the answer by @hjpotter92.
However, their approach can be optimized even more. Note that there is the \$O(k)\$ check from not in
. This is because when you check if an element is in
a list, it goes through the whole list and tries to find it.
A set
on the other hand stores elements via their hashes, giving you \$O(1)\$ in
performance.
If you don't care about the order of elements, you can just pass the input directly to set
:
numbers = [2, 2, 4, 4, 6, 6]
uniques = list(set(numbers))
If you do, however, care about maintaining the order of elements (and always using the position of where the element first appeared), you have to fill both a list
and a set
:
uniques = []
seen = set()
for number in numbers:
if number not in seen:
uniques.append(number)
seen.add(number)
print(uniques)
There are two caveats here, though:
- This takes additional memory, specifically \$O(k)\$, where \$k\$ is the number of unique elements.
- This only works if all elements of the input list are "hashable". This basically boils down to them being not mutable, i.e. you can't use it with a list of lists or dicts. Numbers and strings are perfectly fine, though.
Another thing you will probably learn about, if you haven't already, are functions. They allow you to encapsulate some functionality in one place, give it a name and reuse it:
def unique(x):
uniques = []
seen = set()
for number in numbers:
if number not in seen:
uniques.append(number)
seen.add(number)
return uniques
numbers = [2, 2, 4, 4, 6, 6]
print(unique (numbers))
Actually, there are two more reasons why your teacher's solution is better:
- You mutate the input list when you do
pop
. This means that you would have to make a copy if you need the original list afterwards.
- Your teacher's code works as long as
numbers
is iterable, i.e. you can do for x in numbers
. Your code relies on less universal methods like pop
, count
and index
which are not implemented by all data structures. Being able to be iterated over is very common, though.
numbers = list(set(numbers))
\$\endgroup\$set(numbers)
will do the job \$\endgroup\$