Smartest Way to Find Lonely Integer(s) in Python

One Line Code

ABHISHEK GUPTA
2 min readMay 18, 2022

Problem Statement:

Find the unique element(s) from a given array that only occurs once.

Sample Data:

An array of integers,

a = [2, 4, 4,3, 5, 2, 3]

Further Elaboration:

Write a function that finds the lonely integer among an array of integers where except one, rest of the integers have frequency of occurrences more than one.

Expected return:

int: the element(s) that occurs only once.

Photo by Hitesh Choudhary on Unsplash

The aim of this article is to demonstrate the smartest way to find the lonely integers. There are multiple ways you can solve the problem however, in one of the solutions I will show how can you solve this in just one line of code.

Note: the expected output is an integer, and not a list.

In case, if it was not asked to write as a function, we could use * (asterisk) to print the expected result as shown below:

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

But because, we have to write in a function form, we can not directly use *. Here are other different ways to solve the problem:

Solution: 1 (Normal for loop with condition)

def lonelyinteger(a):
for val in a:
if a.count(val) == 1:
result = val
return result

Solution: 2 (List Comprehension)

def lonelyinteger(a):
result = [val for val in a if a.count(val) ==1]
for i in result:
return i

Solution: 3 (List Comprehension & join)

def lonelyinteger(a):
result = [str(val) for val in a if a.count(val) ==1]
return '\n'.join(result)

Solution: 4 (Master Solution)

One line code:

def lonelyinteger(a):
return " ".join(str(val) for val in a if a.count(val) == 1)

Update:

As Mr. Felipe T. Farias suggested in the comment and I also agree with him, here is his best performance solution:

import collectionsdef lonelyinteger(a):
return " ".join(str(val) for val,count in collections.Counter(a).items() if count == 1)

--

--