# Find all triplets in a list with given sum in Python

In a list of numbers we want to find out which three elements can join to give a certain sum. We call it a triplet. And in the list there can be many such triplets. For example, the sum 10 can be generated form numbers 1,6,3 as well as 1,5,4. In this article we will see how to find out all such triplets from a given list of numbers.

## Using range and temp variables

This is the traditional approach in which we will create temporary variables. These variables will hold the elements from the list and check if their sum is equating to the required value. Then it will keep accumulating such variables into the final result set.

## Example

Live Demo

def SumTriplets(listA, sum):
trpltcnt = 0
res = []

for i in range(0, len(listA) - 1):

s = set()
tmp = []

tmp.append(listA[i])

current_sum = sum - listA[i]

for j in range(i + 1, len(listA)):

if (current_sum - listA[j]) in s:
trpltcnt += 1

tmp.append(listA[j])

tmp.append(current_sum - listA[j])

# Appending tuple to the final list
res.append(tuple(tmp))
tmp.pop(2)
tmp.pop(1)

return res

listA = [11,12,13,14,15,16,17,18,19,20]

print("Required triplets:\n",SumTriplets(listA, 40))

## Output

Running the above code gives us the following result −

Required triplets:
[(11, 15, 14), (11, 16, 13), (11, 17, 12), (12, 15, 13)]

## Example

Live Demo

from itertools import combinations

listA = [11,12,13,14,15,16,17,18,19,20]

def fsum(val):
return sum(val) == 40

res = list(filter(fsum,list(combinations(listA, 3))))

print("Required triplets:\n",res)

## Output

Running the above code gives us the following result −

Required triplets:
[(11, 12, 17), (11, 13, 16), (11, 14, 15), (12, 13, 15)]