-1

I have only recently started learning Python, and have no experience coding. I'm trying to write code that, given a list of numbers, returns another (ordered) list of numbers without any of the duplicates present in the first list.

The following code seems to work:

nums = [2, 2, 1, 3]
r = []
for i in nums:
    if i not in r:
        r.append(i)
print(sorted(r))

Output is:

[1, 2, 3]

I then tried the same using list comprehension, but apparently got something wrong. This is what I tried:

nums = [2, 2, 1, 3]
r = []
r = sorted([i for i in nums if i not in r])
print(r)

And this is the output:

[1, 2, 2, 3]

What did I do wrong?

mforn
  • 13
  • 3
  • 6
    `r` doesn't get updated in list comprehension - it stays at `[]` until sorted is done and result assigned to `r`. – SomeDude Jul 30 '20 at 18:44
  • Does this answer your question? [How to remove duplicate items from a list using list comprehension?](https://stackoverflow.com/questions/10549345/how-to-remove-duplicate-items-from-a-list-using-list-comprehension) – wjandrea Jul 30 '20 at 18:58
  • I'm really not sure why this question was voted down and closed as "not suitable for this site". It's a perfectly valid question, though it's already been asked. – wjandrea Jul 30 '20 at 19:03
  • @stovfl could you chime in on why you voted to close the question? Keep in mind this is OP's first post. – wjandrea Jul 30 '20 at 19:04
  • @MrNobody33 could you chime in on why you voted to close the question? Keep in mind this is OP's first post. – wjandrea Jul 30 '20 at 19:04
  • 1
    @wjandrea, it does answer it, thanks a lot! – mforn Jul 30 '20 at 19:11

1 Answers1

2

First of all, r doesn't update in your list comprehension ([i for i in nums if i not in r]), so it will be empty every time that you check your condition.

Also, for sorting unique list with numbers, use set like: sorted(set(nums))

mjrezaee
  • 1,100
  • 5
  • 9