Search code examples
pythonpython-3.xlistuniquelist-comprehension

Why list comprehension doesn't work the same as code without comprehension?


I tried to create a simple function to remove duplicates from the list.

x = [7, 7, 5, 6, 8, 9, 9, 0]
for n, i in enumerate(x):
  if i in x[n + 1:]:
    x.remove(i)
print(x)

Output:

[7, 5, 6, 8, 9, 0]

This code works fine as far as I know.

But when I'm trying to convert it in comprehension list form, I'm getting wrong output:

def unique_list(lst):
  return [lst.remove(i) for n, i in enumerate(lst) if i in lst[n + 1:]]

x = [7, 7, 5, 6, 8, 9, 9, 0]
print(unique_list(x))

Output:

[None, None]

So, the question is - why the output is different?


Solution

  • Your two ways of writing the functionality of set(x) are not identical. While the first is using a side-effect of x.remove(..) to "return" your modified list in place, the second form returns a newly created list.

    The elements of that list are formed by what is returned by the expression lst.remove(i), which is None as Manuel already has pointed out in their answer.

    You receive [None, None] because your code calls lst.remove 2 times. So your function unique_list could be called count_duplicates, just with a peculiar output format (with the length of a list of None encoding the result instead of a straightforward int).