Python - List with most unique elements
Last Updated :
05 May, 2023
Sometimes, while working with data, we can have a problem in which we need to compute the list which has most number of unique elements. This can have application in many domains. Lets discuss certain ways in which this task can be performed.
Method #1 : Using list comprehension + max() + set() The combination of above functionalities can be used to solve this problem. In this, we compute the maximum occurring elements using max() and reduce the logic to uniqueness using set().
Python3
# Python3 code to demonstrate
# List with most unique elements
# using list comprehension + max() + set()
# Initializing lists
test_list1 = [1, 3, 4, 4, 4, 3, 3, 2, 2, 1]
test_list2 = [1, 3, 4, 6, 7]
test_list3 = [4, 5, 4, 3, 6, 7, 8]
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
print("The original list 3 is : " + str(test_list3))
# List with most unique elements
# using list comprehension + max() + set()
res = [ele for ele in [set(test_list1), set(test_list2), set(test_list3)]
if len(ele) == max([len(sub) for sub in [set(test_list1), set(test_list2), set(test_list3)]])][0]
# printing result
print ("List with Most unique values : " + str(list(res)))
Output : The original list 1 is : [1, 3, 4, 4, 4, 3, 3, 2, 2, 1]
The original list 2 is : [1, 3, 4, 6, 7]
The original list 3 is : [4, 5, 4, 3, 6, 7, 8]
List with Most unique values : [3, 4, 5, 6, 7, 8]
Time Complexity: O(n*n) where n is the number of elements in the list “test_list”.
Auxiliary Space: O(n) where n is the number of elements in the list “test_list”.
Method #2 : Using max() + set() + key This task can also be performed using combination of above functions. In this, we extract the maximum frequency list using max() and key argument len.
Python3
# Python3 code to demonstrate
# List with most unique elements
# using key + max() + set()
# Initializing lists
test_list1 = [1, 3, 4, 4, 4, 3, 3, 2, 2, 1]
test_list2 = [1, 3, 4, 6, 7]
test_list3 = [4, 5, 4, 3, 6, 7, 8]
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
print("The original list 3 is : " + str(test_list3))
# List with most unique elements
# using key + max() + set()
temp = [set(test_list1), set(test_list2), set(test_list3)]
res = max(temp, key = len)
# printing result
print ("List with Most unique values : " + str(list(res)))
Output : The original list 1 is : [1, 3, 4, 4, 4, 3, 3, 2, 2, 1]
The original list 2 is : [1, 3, 4, 6, 7]
The original list 3 is : [4, 5, 4, 3, 6, 7, 8]
List with Most unique values : [3, 4, 5, 6, 7, 8]
Time Complexity: O(n*n), where n is the length of the list test_list
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the res list
Method #3 : Using Counter() function and conditional statements
Python3
# Python3 code to demonstrate
# List with most unique elements
from collections import Counter
# Initializing lists
test_list1 = [1, 3, 4, 4, 4, 3, 3, 2, 2, 1]
test_list2 = [1, 3, 4, 6, 7]
test_list3 = [4, 5, 4, 3, 6, 7, 8]
# printing original lists
print("The original list 1 is :" + str(test_list1))
print("The original list 2 is :" + str(test_list2))
print("The original list 3 is :" + str(test_list3))
# List with most unique elements
freq1 = Counter(test_list1)
freq2 = Counter(test_list2)
freq3 = Counter(test_list3)
res = freq1.keys()
if(len(freq2) >= len(res)):
res = freq2.keys()
if(len(freq3) >= len(res)):
res = freq3.keys()
res = list(res)
res.sort()
# printing result
print("List with Most unique values : " + str(list(res)))
OutputThe original list 1 is :[1, 3, 4, 4, 4, 3, 3, 2, 2, 1]
The original list 2 is :[1, 3, 4, 6, 7]
The original list 3 is :[4, 5, 4, 3, 6, 7, 8]
List with Most unique values : [3, 4, 5, 6, 7, 8]
Time Complexity: O(N)
Auxiliary Space: O(N)
Using Counter() + max()
Python3
#Using Counter() + max()
#Count frequency of each list
#Get the maximum frequency among the lists using max() function
#Return the list with maximum frequency
from collections import Counter
def most_unique_elements(lists):
freq_list = [Counter(lst) for lst in lists]
max_freq = max(freq_list, key=len)
return list(max_freq.keys())
#test
test_lists = [[1, 3, 4, 4, 4, 3, 3, 2, 2, 1], [1, 3, 4, 6, 7], [4, 5, 4, 3, 6, 7, 8]]
print(most_unique_elements(test_lists))
Time complexity: O(nk), n is the number of lists and k is the average length of the lists
Auxiliary Space: O(nk)
Explanation:
The function takes a list of lists as input, and computes the frequency of elements in each list using Counter() function.
The function returns the list with maximum frequency among all lists.
Method #5 : Using numpy:
- Initialize three lists of integers.
- Create a new list 'lists' that contains all three lists.
- Create a new list 'unique_counts' that contains the number of unique elements in each of the lists using a list comprehension.
- Get the index of the maximum value in 'unique_counts' using the index() method.
- Get the list at the index found in step 4 from the 'lists' list.
- Print the result.
Python3
import numpy as np
# Initializing lists
test_list1 = [1, 3, 4, 4, 4, 3, 3, 2, 2, 1]
test_list2 = [1, 3, 4, 6, 7]
test_list3 = [4, 5, 4, 3, 6, 7, 8]
# printing original lists
print("The original list 1 is :" + str(test_list1))
print("The original list 2 is :" + str(test_list2))
print("The original list 3 is :" + str(test_list3))
lists = [test_list1, test_list2, test_list3]
unique_counts = [len(np.unique(lst)) for lst in lists]
res = lists[unique_counts.index(max(unique_counts))]
# printing result
print("List with Most unique values : " + str(res))
#This code is contributed by Jyothi Pinjala.
Output:
The original list 1 is :[1, 3, 4, 4, 4, 3, 3, 2, 2, 1]
The original list 2 is :[1, 3, 4, 6, 7]
The original list 3 is :[4, 5, 4, 3, 6, 7, 8]
List with Most unique values : [4, 5, 4, 3, 6, 7, 8]
Time complexity:
The creation of the 'lists' list takes O(1) time, since we are just concatenating three lists.
The creation of the 'unique_counts' list takes O(n) time, where n is the total number of elements in all three lists, since we are iterating through each list and calling np.unique() on each one.
The call to index() takes O(1) time.
The retrieval of the list at the index found in step 4 takes O(1) time.
Therefore, the overall time complexity is O(n).
Auxiliary Space:
The space used by the 'lists' list is O(n), where n is the total number of elements in all three lists.
The space used by the 'unique_counts' list is O(3), since it has three elements.
The space used by the 'res' variable is O(k), where k is the number of unique elements in the largest list.
Therefore, the overall space complexity is O(n).
Method 6 : Using the built-in function sorted() and lambda function.
Steps
Initialize the given lists.
Create a list of sets using list comprehension.
Sort the list of sets in decreasing order of their lengths.
Return the first set from the sorted list as it will have the most unique elements.
Convert the set to a list and print the result.
Python3
# Python3 code to demonstrate
# List with most unique elements
# using sorted() and lambda function
# Initializing lists
test_list1 = [1, 3, 4, 4, 4, 3, 3, 2, 2, 1]
test_list2 = [1, 3, 4, 6, 7]
test_list3 = [4, 5, 4, 3, 6, 7, 8]
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
print("The original list 3 is : " + str(test_list3))
# List with most unique elements
# using sorted() and lambda function
res = sorted([set(test_list1), set(test_list2), set(test_list3)], key=lambda x: len(x), reverse=True)[0]
# printing result
print("List with Most unique values : " + str(list(res)))
OutputThe original list 1 is : [1, 3, 4, 4, 4, 3, 3, 2, 2, 1]
The original list 2 is : [1, 3, 4, 6, 7]
The original list 3 is : [4, 5, 4, 3, 6, 7, 8]
List with Most unique values : [3, 4, 5, 6, 7, 8]
The time complexity of this approach is O(n log n), where n is the total number of elements in all the given lists.
The auxiliary space of this approach is O(n), where n is the total number of elements in all the given lists.
Similar Reads
Python - First K unique elements
Sometimes, while working with Python Lists, we can have a problem in which we need to extract first K unique elements. This means we need to extract duplicate if they occur in first K elements as well. This can essentially make count of first K unique elements more than K. This kind of problem can h
3 min read
Python - Elements with same index
Given a List, get all elements that are at their index value. Input : test_list = [3, 1, 8, 5, 4, 10, 6, 9]Â Output : [1, 4, 6]Â Explanation : These elements are at same position as its number.Input : test_list = [3, 10, 8, 5, 14, 10, 16, 9]Â Output : []Â Explanation : No number at its index. Method
5 min read
Python | List Element Count with Order
Sometimes, while working with lists or numbers we can have a problem in which we need to attach with each element of list, a number, which is the position of that element's occurrence in that list. This type of problem can come across many domains. Let's discuss a way in which this problem can be so
4 min read
Python | Unique pairs in list
Sometimes, while working with python list, we can have a binary matrix ( Nested list having 2 elements ). And we can have a problem in which we need to find the uniqueness of a pair. A pair is unique irrespective of order, it doesn't appear again in list. Let's discuss certain way in which this task
6 min read
Python | Count unique sublists within list
Given a list of lists, the task is to find the count of unique sublists within list. Examples: Input: [['Geek', 'for', 'geeks'], ['geeks', 'for'], ['for', 'Geeks', 'geek'], ['Geek', 'for', 'geeks']] Output: {('geeks', 'for'): 1, ('for', 'Geeks', 'geek'): 1, ('Geek', 'for', 'geeks'): 2} Below are som
2 min read
Python - Dictionaries with Unique Value Lists
Given List of dictionaries with list values, extract unique dictionaries. Input : [{'Gfg': [2, 3], 'is' : [7, 8], 'best' : [10]}, {'Gfg': [2, 3], 'is' : [7, 8], 'best' : [10]}] Output : [{'Gfg': [2, 3], 'is': [7, 8], 'best': [10]}] Explanation : Both are similar dictionaries, and hence 1 is removed.
4 min read
String with Most Unique Characters - Python
The task of finding the string with the most unique characters in a list involves determining which string contains the highest number of distinct characters. This is done by evaluating each string's distinct elements and comparing their counts. The string with the greatest count of unique character
4 min read
Find Unique Elements from Tuple in Python
Tuples are immutable built-in data type in Python that can store multiple values in it. Extracting Unique Elements from a Tuple in Python can be done through two different approaches. Examples: Input: (1, 2, 13, 4, 3, 12, 5, 7, 7, 2, 2, 4)Output: (1, 2, 3,4,5,12,13)Input: ('Apple', 'Mango', 'Banana'
5 min read
Python - Summation of Unique elements
This article focuses on one of the operation of getting the unique list from a list that contains a possible duplicates and performing its summation. This operations has large no. of applications and hence itâs knowledge is good to have. Method 1 : Naive method + sum() In naive method, we simply t
5 min read
Uncommon Elements in Lists of List - Python
We are given two lists of lists and our task is to find the sublists that are uncommon between them. (a sublist is considered uncommon if it appears in only one of the lists and not in both.) For example: a = [[1, 2], [3, 4], [5, 6]] and b = [[3, 4], [5, 7], [1, 2]] then the output will be [[5, 6],
4 min read