Python - Unique Values Multiplication


List in python allows duplicate entries, that is we can have the same value twice in a list. That is useful in most cases, but sometimes there is a need to remove the duplicate elements to perform certain operations. In this article we will focus on how we can take up the unique values removing duplicates from a list of integers and finding their product. It has a wide use case scenario and we will try and discuss all possible ways to generate the output.

Method 1: Set Implementation

Set in python is unordered data collection that is iterable, mutable but has no duplicate elements. So this can be helpful for us to get the unique set of data from our list. The set() function helps us achieve the same. Let us start coding.

Example

def prodUniq(listEnter):
   res = 1
   for item in listEnter:
      res *= item
   return res

#initial list
userList = [24, 15, 24, 41, 22, 11, 11, 51]
#unique list
uniqList = list(set(userList))
#product output
res = prodUniq(uniqList)

print("User entered list: ",userList)
print("Unique Values List: ",uniqList)
print("Unique Values Multiplication: ",res)

Output

User entered list:  [24, 15, 24, 41, 22, 11, 11, 51]
Unique Values List:  [41, 11, 15, 51, 22, 24]
Unique Values Multiplication:  182167920

Method 2: Using Another List

Now we will try and get the product without the help of other collections of data but list. We will take help from an empty list to filter out the unique elements and then find the product. Let us keep the product function the same.

Example

def prodUniq(listEnter):
   res = 1
   for item in listEnter:
      res *= item
   return res

#initial list
userList = [24, 15, 24, 41, 22, 11, 11, 51]
#unique list generation
uniqList = []
for item in userList:
   if item not in uniqList:
      uniqList.append(item)

res = prodUniq(uniqList)

print("User entered list: ",userList)
print("Unique Values List: ",uniqList)
print("Unique Values Multiplication: ",res)

Output

User entered list:  [24, 15, 24, 41, 22, 11, 11, 51]
Unique Values List:  [24, 15, 41, 22, 11, 51]
Unique Values Multiplication:  182167920

A simple approach, where we iterate our existing list to check if any item is present in the empty unique list and insert the same if not. Thus we can easily filter out the duplicate elements and then pass it in our existing product function to get the product.

  • Time Complexity − O()

  • Auxiliary Space − O()

Method 3: List Comprehension

List comprehension is a shorter syntax to generate a new list from an existing one. Let us try and use it to get our unique list. List comprehension helps us shorten our code here.

Example

def prodUniq(listEnter):
   res = 1
   for item in listEnter:
      res *= item
   return res

#initial list
userList = [24, 15, 24, 41, 22, 11, 11, 51]
#unique list generation
uniqList = [item for index, item in enumerate(userList) if item not in userList[:index]]

res = prodUniq(uniqList)

print("User entered list: ",userList)
print("Unique Values List: ",uniqList)
print("Unique Values Multiplication: ",res)

Output

User entered list:  [24, 15, 24, 41, 22, 11, 11, 51]
Unique Values List:  [24, 15, 41, 22, 11, 51]
Unique Values Multiplication:  182167920
  • Time Complexity − O()

  • Auxiliary Space − O()

Method 4: Using Counter

Inside the collections module we have a dictionary subclass used specifically for counting hashed values. Counter stores the values as keys and their count as values in the dictionary. We can take help from the keys to get the unique list.

Example

from collections import Counter

def prodUniq(listEnter):
   res = 1
   for item in listEnter:
      res *= item
   return res

#initial list
userList = [24, 15, 24, 41, 22, 11, 11, 51]

#count dictionary generated by counter
counterDict = Counter(userList)

#unique list generation
uniqList = counterDict.keys()

res = prodUniq(uniqList)

print("User entered list: ",userList)
print("Counter generated dict: ",counterDict)
print("Unique Values List: ",uniqList)
print("Unique Values Multiplication: ",res)

Output

User entered list:  [24, 15, 24, 41, 22, 11, 11, 51]
Counter generated dict:  Counter({24: 2, 11: 2, 15: 1, 41: 1, 22: 1, 51: 1})
Unique Values List:  dict_keys([24, 15, 41, 22, 11, 51])
Unique Values Multiplication:  182167920

The output clearly shows what the Counter() function actually does. We have cleverly utilized the keys from the Counter generated dictionary as they represent the unique values from the list and ignored its counts(value pairs). Then our simple product function.

  • Time Complexity − O()

  • Auxiliary Space − O()

Method 5: Dictionary to Track Occurrences

A dictionary can be used to keep track of each element in the list. By iterating through the list and updating the dictionary we can get the unique values from the list and generate their product. It is similar to the counter approach only excluding inbuilt functions.

Example

def prodUniq(listEnter):
   res = 1
   #dictionary to keep track of each item
   emptyDict = {}
   for item in listEnter:
      if item not in emptyDict:
         emptyDict[item] = 1
         res *= item
      return res

#initial list
userList = [24, 15, 24, 41, 22, 11, 11, 51]
#product
res = prodUniq(userList)

print("User entered list: ",userList)
print("Unique Values Multiplication: ",res)

Output

User entered list:  [24, 15, 24, 41, 22, 11, 11, 51]
Unique Values Multiplication:  182167920
  • Time Complexity − O()

  • Auxiliary Space − O()

Method 6: Using Numpy

Numpy is a very popular library. It consists of powerful tools used extensively in statistical and scientific calculations. The unique and prod functions in numpy help us easily get our product output.

Example

import numpy as np

#initial list
userList = [24, 15, 24, 41, 22, 11, 11, 51]

#unique list
uniqList = np.unique(userList)

#product
res = np.prod(uniqList)

print("User entered list: ",userList)
print("Unique list using numpy: ",uniqList)
print("Unique Values Multiplication using numpy: ",res)

Output

User entered list:  [24, 15, 24, 41, 22, 11, 11, 51]
Unique list using numpy:  [11 15 22 24 41 51]
Unique Values Multiplication using numpy:  182167920

The unique function generates a list of non duplicate sorted elements from the existing list. The prod function on the other hand generates the product of elements inside the list passed.

  • Time Complexity − O()

  • Auxiliary Space − O()

Method 7: Using itertools

Python helps us with a powerful itertools module with tools and functions helping in efficient looping. In the itertools library we have a groupby() function that helps us group unique elements. In this method we will try and use this function to effectively create our unique list.

Example

import itertools

#initial list
userList = [24, 15, 24, 41, 22, 11, 11, 51]

#unique list
uniqList = [key for key, group in itertools.groupby(sorted(userList))]

#product
res = 1
for item in uniqList:
   res *=item

print("User entered list: ",userList)
print("Unique list: ",uniqList)
print("Unique Values Multiplication: ",res)

Output

User entered list:  [24, 15, 24, 41, 22, 11, 11, 51]
Unique list:  [11, 15, 22, 24, 41, 51]
Unique Values Multiplication:  182167920

It is important to use sorted to ensure groupby() functions properly. The itertools.groupby() function actually produces (key, group) pairs for each unique key and associated group. For our use case we only need the unique values so we extract the key part of each pair using the list comprehension. Once we have a unique list, this time we use a simple for loop where we multiply each item in the list with a pre-created resultant value initialized to unity.

  • Time Complexity − O()

  • Auxiliary Space − O()

Conclusion

Here comes the end to this article but a beginning to explore the other possibilities. Each method discussed above approaches in a different way and depends on the requirements where we can implement them. Understanding these small techniques in python helps us in larger projects ahead.

Try and implement your own version of the seven methods discussed above. The set and math.prod() function in Python 3.8+ is a one liner solution to our unique values multiplication problem statemen. Check it out, Happy coding.

Updated on: 02-Nov-2023

62 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements