0

Consider I have a list, n_list

n_list = [2, 4, 4, 5, 2]

My goal is get the unique val that has frequency of occurrence is only 1 in the list.

I am able to do as follows:

result = [val for val in n_list if n_list.count(val) == 1]
for i in result:
    print(i)

However, I would like to get the result of list comprehension with the list and just the value. Basically, without writing a separate for loop for it, that means, without:

for i in result:
    print(i)

but using list comprehension.

sargupta
  • 953
  • 13
  • 25

1 Answers1

0

Just figured out, we can print the result using *

print(*[val for val in n_list if n_list.count(val) == 1])

However, when tested as a function, it gives error:

def singleVal(n_list):
    return(*[val for val in n_list if n_list.count(val) ==1])
    
singleVal(n_list)

Error: Can’t use started expression here.

sargupta
  • 953
  • 13
  • 25
  • the parenthesis in the return is not needed (and i believe syntactically wrong) I don't think you need them or the star. Otherwise this solution works. – Nicholas Lawrence May 18 '22 at 02:36
  • Added `*`because I want only value and not the list. Removing `*`will result a list. @NicholasLawrence – sargupta May 18 '22 at 02:49
  • In that case you could add [0] to the end of the list comprehension – Nicholas Lawrence May 18 '22 at 03:12
  • That's correct, but how can I make it dynamic (independent of specific number, e.g. 0 in this case) – sargupta May 18 '22 at 03:24
  • Hmm - if you are only trying to avoid iterating once you could do the for loop and only return after the if count evaluation. But if you are trying to do this within a comprehension specifically you could explore this https://stackoverflow.com/questions/32139885/yield-in-list-comprehensions-and-generator-expressions – Nicholas Lawrence May 18 '22 at 09:47