Open In App

Python – List product excluding duplicates

Last Updated : 13 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

This article focuses on one of the operations of getting the unique list from a list that contains a possible duplicated and finding its product. This operation has a large no. of applications and hence its knowledge is good to have.

Method 1: Naive method 

In the naive method, we simply traverse the list and append the first occurrence of the element in new list and ignore all the other occurrences of that particular element. The task of performing the product is done using loop.

Python3




# Python 3 code to demonstrate
# Duplication Removal List Product
# using naive methods
 
# getting Product
 
 
def prod(val):
    res = 1
    for ele in val:
        res *= ele
    return res
 
 
# initializing list
test_list = [1, 3, 5, 6, 3, 5, 6, 1]
print("The original list is : " + str(test_list))
 
# using naive method
# Duplication Removal List Product
res = []
for i in test_list:
    if i not in res:
        res.append(i)
res = prod(res)
 
# printing list after removal
print("Duplication removal list product : " + str(res))


Output : 

The original list is : [1, 3, 5, 6, 3, 5, 6, 1]
Duplication removal list product : 90

 

Time Complexity: O(n^2)
Auxiliary Space: O(n)

 
Method 2: Using list comprehension 

This method has working similarly to the above method, but this is just a one-liner shorthand for a longer method done with the help of list comprehension. 

Python3




# Python 3 code to demonstrate
# Duplication Removal List Product
# using list comprehension
 
# getting Product
 
 
def prod(val):
    res = 1
    for ele in val:
        res *= ele
    return res
 
 
# initializing list
test_list = [1, 3, 5, 6, 3, 5, 6, 1]
print("The original list is : " + str(test_list))
 
# using list comprehension
# Duplication Removal List Product
res = []
[res.append(x) for x in test_list if x not in res]
res = prod(res)
 
# printing list after removal
print("Duplication removal list product : " + str(res))


Output : 

The original list is : [1, 3, 5, 6, 3, 5, 6, 1]
Duplication removal list product : 90

 

Time Complexity: O(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 3: Using set() and functools.reduce() [Intermediate]

Checking for list membership is O(n) on average, so building up the list of non-duplicates becomes an O(n2) operation on average. One can transform a list into a set to remove the duplicates which is O(n) complexity.  After this the product of the set elements can be calculated in the usual fashion by iterating over them or, to further reduce the code, the reduce() method from functools module can be used. As the documentation explains:

Apply function of two arguments cumulatively to the items of iterable, from left to right, so as to reduce the iterable to a single value.

Here’s how the code can be reduced to a couple of lines

Python3




import functools
 
functools.reduce(lambda x, y: x*y, set([1, 3, 5, 6, 3, 5, 6, 1]), 1)


What this does is applies a lambda to the set obtained from the list. The lambda takes in two arguments x, and y and returns the product of the two numbers. This lambda is applied to all the elements in the list cumulatively i.e.

lambda(lambda(lambda(1, 3), 5), 6)….

which yields the final product as 90. It’s always prudent to add in an initial argument to the reduce() function to handle empty sequences so that the default value can be returned. In this case, since it’s a product, that value should be 1. Thus something like

functools.reduce(lambda x,y: x*y, set([]), 1)

yields the output 1, despite the list being empty. This initial argument is added before the values in the sequence and the lambda is applied as usual.

lambda(lambda(lambda(lambda(1,1 ), 3), 5), 6)….

Method 4: Using set() to remove duplicates and for loop to find product

Python3




# Python 3 code to demonstrate
# Duplication Removal List Product
 
test_list = [1, 3, 5, 6, 3, 5, 6, 1]
print("The original list is : " + str(test_list))
 
# using naive method
# Duplication Removal List Product
x = list(set(test_list))
prod = 1
for i in x:
    prod *= i
 
# printing list after removal
print("Duplication removal list product : " + str(prod))


Output

The original list is : [1, 3, 5, 6, 3, 5, 6, 1]
Duplication removal list product : 90

Time complexity : O(n)

Auxiliary Space : O(n), where n is length of test_list.

Method 5: Using math.prod()

The product of distinct elements can be calculated by storing elements in set to remove duplicates, then using math.prod() function to calculate the product.

Python3




import math
 
def product(list):
    s = set(list)
    return (math.prod(s))
 
 
l = [1, 3, 5, 6, 3, 5, 6, 1]
print(product(l))


Output

90

Method 6: Using numpy

Note: Install numpy module using command “pip install numpy”

The numpy library in Python provides a convenient way to perform this operation as well. The numpy library has a prod method that can be used to calculate the product of the elements in an array. To remove duplicates from the list, you can convert the list to a numpy array, use the unique method to get the unique elements, and then calculate the product using the prod method. Here’s an example:

Python3




import numpy as np
  
# initializing list
test_list = [1, 3, 5, 6, 3, 5, 6, 1]
print("The original list is : " + str(test_list))
  
# converting list to numpy array and finding unique elements
unique_array = np.unique(np.array(test_list))
  
# finding product of unique elements
result = np.prod(unique_array)
  
# printing result
print("Duplication removal list product : " + str(result))


Output:

The original list is : [1, 3, 5, 6, 3, 5, 6, 1]
Duplication removal list product : 90

The time complexity of this approach is O(n) for finding the unique elements using the unique method, and O(m), where m is the number of unique elements, for calculating the product using the prod method. The space complexity is O(m) for storing the unique elements in the numpy array.



Similar Reads

Python | Merging duplicates to list of list
Sometimes, we need to perform the conventional task of grouping some like elements into a separate list and thus forming a list of lists. This can also help in counting and also get the sorted order of elements. Let's discuss certain ways in which this can be done. Method #1: Using collections.Counter() This particular function can prove to be quit
6 min read
Python Remove Duplicates from a List
The job is simple. We need to take a list, with duplicate elements in it and generate another list that only contains the element without the duplicates in them. Examples: Input : [2, 4, 10, 20, 5, 2, 20, 4] Output : [2, 4, 10, 20, 5] Input : [28, 42, 28, 16, 90, 42, 42, 28] Output : [28, 42, 16, 90] We can use not in on list to find out the duplic
3 min read
Python | Program to print duplicates from a list of integers
Given a list of integers with duplicate elements in it. The task is to generate another list, which contains only the duplicate elements. In simple words, the new list should contain elements that appear as more than one. Examples: Input : list = [10, 20, 30, 20, 20, 30, 40, 50, -20, 60, 60, -20, -20] Output : output_list = [20, 30, -20, 60]Input :
5 min read
Python | Program to count duplicates in a list of tuples
Given a list of tuples, write a Python program to check if an element of the list has duplicates. If duplicates exist, print the number of occurrences of each duplicate tuple, otherwise print "No Duplicates". Examples: Input : [('a', 'e'), ('b', 'x'), ('b', 'x'), ('a', 'e'), ('b', 'x')] Output : ('a', 'e') - 2 ('b', 'x') - 3 Input : [(0, 5), (6, 9)
6 min read
Python | Remove consecutive duplicates from list
In Python, we generally wish to remove the duplicate elements, but sometimes for several specific usecases, we require to have remove just the elements repeated in succession. This is a quite easy task and having a shorthand for it can be useful. Let's discuss certain ways in which this task can be performed. Method #1 : Using groupby() + list comp
4 min read
Python | Remove all duplicates and permutations in nested list
Given a nested list, the task is to remove all duplicates and permutations in that nested list. Input: [[-11, 0, 11], [-11, 11, 0], [-11, 0, 11], [-11, 2, -11], [-11, 2, -11], [-11, -11, 2]] Output: {(-11, 0, 11), (-11, -11, 2)} Input: [[-1, 5, 3], [3, 5, 0], [-1, 5, 3], [1, 3, 5], [-1, 3, 5], [5, -1, 3]] Output: {(1, 3, 5), (0, 3, 5), (-1, 3, 5)}
4 min read
Python | Combine two lists by maintaining duplicates in first list
Given two lists, the task is to combine two lists and removing duplicates, without removing duplicates in original list. Example: Input : list_1 = [11, 22, 22, 15] list_2 = [22, 15, 77, 9] Output : OutList = [11, 22, 22, 15, 77, 9] Code #1: using extend C/C++ Code # Python code to combine two lists # and removing duplicates, without # removing dupl
6 min read
Python | Remove duplicates from nested list
The task of removing duplicates many times in the recent past, but sometimes when we deal with the complex data structure, in those cases we need different techniques to handle this type of problem. Let's discuss certain ways in which this task can be achieved. Method #1 : Using sorted() + set() This particular problem can be solved using the above
5 min read
Python | Sort given list by frequency and remove duplicates
Problems associated with sorting and removal of duplicates is quite common in development domain and general coding as well. The sorting by frequency has been discussed, but sometimes, we even wish to remove the duplicates without using more LOC's and in a shorter way. Let's discuss certain ways in which this can be done. Method #1 : Using count()
5 min read
Python | Consecutive duplicates all elements deletion in list
Sometimes, while working with Python list, a problem can occur to filter list to remove duplicates. The solution to this has been discussed before. But sometimes, we may have a problem in which we need to delete the duplicate and element itself if it occurs more than 1 in consecution. This type of problem can occur in day-day programming and other
4 min read
Practice Tags :