-2

I need help shortening the following code into one line.

for i in objects:
    if i not in uniq: 
        uniq.append(i)

Im just doing it for a challenge, not going to keep this.

Dav_Did
  • 188
  • 10

3 Answers3

3

The easiest oneliner would be to use a set:

uniq = set(objects)

If you really need a list, you could of course create one from the set:

uniq = list(set(objects))
Mureinik
  • 297,002
  • 52
  • 306
  • 350
  • No, using set would disturb the order of the list. – Dav_Did Dec 06 '20 at 20:30
  • And if you want to sort the list back into the "ordering" of the first list, then you can just throw a `sorted` at it: `sorted(list(set(objects)), key=lambda x: objects.index(x))` – Hampus Larsson Dec 06 '20 at 20:38
1

You can use list comprehension, although this is a bad idea for many reasons

uniq=[]
objects= [9,9,1,2,3,4,5,5,9,9,15,12,33]
[uniq.append(i) for i in objects if i not in uniq]
print(uniq)

outputs:

[9, 1, 2, 3, 4, 5, 15, 12, 33]

Firstly, from a style/readability perspective it's confusing to read, is 'implicit rather than explicit' it adds no value over your FOR loop except to put everything onto one line for no real benefit.

Secondly, it's hard to modify, it's limited to exactly one operation, which might work now but if you need to add a second operation you have to refactor the whole thing

JeffUK
  • 4,107
  • 2
  • 20
  • 34
0
objects= [9,9,1,2,3,4,5,5,9,9,15,12,33]    
uniq=[ele for i,ele in enumerate(objects) if objects.index(ele)==i]

outputs

[9, 1, 2, 3, 4, 5, 15, 12, 33]
angelogro
  • 124
  • 8