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.
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.
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))
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
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]