Search code examples
pythonone-liner

One line coding with if statement inside for loop


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.


Solution

  • 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