4
source=[1,2,3,4,2,3,5,6]

dst=[]
for item in source:
    if item not in dst:
        dst.append(item)

print(dst) # [1,2,3,4,5,6]

Can I simplify code above something like this:

dst=[item for item in [1,2,3,4,2,3,5,6] if item not in 'this array']

Thanks

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555

5 Answers5

6

No, list comprehensions cannot be self-referential.

You seem to want to remove duplicates from a list. See this and this questions for a boatload of approaches to this problem.

timgeb
  • 76,762
  • 20
  • 123
  • 145
4

A set is probably what you are looking for, since you cannot refer to this array while it's being created:

>>> source = [1,2,3,4,2,3,5,6]
>>> set(source)
{1, 2, 3, 4, 5, 6}

If you do want to keep original order, though, you can keep track of what you have already added to dst with a set (seen):

>>> source = [1,2,3,4,2,3,5,6]
>>> seen = set()
>>> dst = []
>>> for i in source:
>>>     if i not in seen:
>>>         dst.append(i)
>>>         seen.add(i)
>>>
>>> dst
[1, 2, 3, 4, 5, 6]
grovina
  • 2,999
  • 19
  • 25
3

You can't reference dst from within the list comprehension, but you can check the current item against the previously iterated items in source by slicing it on each iteration:

source = [1, 2, 3, 4, 2, 3, 5, 6]
dst = [item for i, item in enumerate(source)
       if item not in source[0:i]]

print(dst)  # [1, 2, 3, 4, 5, 6]
101
  • 8,514
  • 6
  • 43
  • 69
0

If using if and for is your requirement How about this?

[dst.append(item) for item in source if item not in dst]
Sagun Shrestha
  • 1,188
  • 10
  • 23
0

Well instead of creating new list you can modify your existing list with list comprehension as shown below:

In [1]: source
Out[1]: [1, 9, 2, 5, 6, 6, 4, 1, 4, 11]

In [2]: [ source.pop(i) for i in range(len(source))[::-1] if source.count(source[i]) > 1 ]
Out[2]: [4, 1, 6]

In [3]: source
Out[3]: [1, 9, 2, 5, 6, 4, 11]

As another approach you can first get unique list with set and then sort it with reference to source index value as follow:

source = [1, 9, 2, 5, 6, 6, 4, 1, 4, 11]
d = list(set(source))
d.sort(key=source.index)
print(d)  # [1, 9, 2, 5, 6, 4, 11]
Gahan
  • 4,075
  • 4
  • 24
  • 44