# Python | Three-element sum in a list

Loops | Python Methods and Functions | String Variables

Method # 1: Using Nested Loops

This is a naive method in which this particular problem can be solved and uses an outer loop to iterate over each element and the inner loop checks the remaining difference by adding pairs to the result.

 ` # Python3 demo code ` ` Sum of elements # 3 ` ` # using nested loops `   ` # initializing list ` ` test_list ` ` = ` ` [` ` 4 ` `, ` ` 1 ` `, ` ` 3 ` `, ` ` 2 ` `, ` ` 6 ` `, ` ` 5 ` `] `   ` # initial amount ` ` sum ` ` = ` ` 9 `   ` # print original list ` ` print ` ` (` ` "The original list:" ` ` + ` ` str ` ` (test_list)) `   ` # using nested loops ` ` Sum of # 3 elements ` ` res ` ` = ` ` [] ` ` for ` ` i ` ` in ` ` range ` ` (` ` 0 ` `, ` ` len ` ` (test_list) ` ` - ` ` 2 ` `): ` ` for ` ` j ` ` in ` ` range ` ` (i ` ` + ` ` 1 ` `, ` ` len ` ` (test_list) ` ` - ` ` 1 ` `): ` ` for ` ` k ` ` in ` ` range ` ` (j ` ` + ` ` 1 ` `, ` ` len ` ` (test_list)): ` ` if ` ` test_list [i] ` ` + ` ` test_list [j] ` ` + ` ` test_list [k] ` ` = ` ` = ` ` sum ` `: ` ` temp ` ` = ` ` [] ` ` temp.append (test_list [i]) ` ` temp.append (test_list [j]) ` ` temp.append (test_list [k] ) ` ` ` ` res.append (` ` tuple ` ` (temp)) `   ` # print result ` ` print ` ` (` ` "The 3 sum element list is:" ` ` + ` ` str ` ` (res)) `

Output:

` The original list: [4, 1, 3, 2, 6, 5] The 3 sum element list is: [(4, 3, 2), (1, 3, 5), (1, 2, 6)] `

Method # 2: Using ` itertools .combination () `
This particular problem can also be accomplished in a succinct manner using a built-in function function. The combination function finds the entire combination that takes K arguments leading to a specific amount.

 ` # Python3 demo code ` ` Sum of # 3 items ` ` # using itertools.combination () ` ` from ` ` itertools ` ` import ` ` combinations `   ` # function to get the sum ` ` def ` ` test (val): ` ` return ` ` sum ` ` (val) ` ` = ` ` = ` ` 9 ` ` `  ` # initializing list ` ` test_list ` ` = ` ` [` ` 4 ` `, ` ` 1 ` `, ` ` 3 ` `, ` ` 2 ` `, ` ` 6 ` `, ` ` 5 ` `] `   ` # initial amount ` ` summation ` ` = ` ` 9 `   ` # prints the original list ` ` print ` ` (` ` "The original list: "` ` + ` ` str ` ` (test_list)) `   ` # using itertools.combination () ` ` Sum of # 3 items ` ` res ` ` = ` ` list ` ` (` ` filter ` ` (test, ` ` list ` ` (combinations (test_list, ` ` 3 ` `)))) ` ` `  ` # print result ` ` print ` ` (` ` "The 3 sum element list is:" ` ` + ` ` str ` ` (res)) `

Exit:

` The o riginal list: [4, 1, 3, 2, 6, 5] The 3 sum element list is: [(4, 3, 2), (1, 3, 5), (1, 2, 6)] `