In this Python tutorial, we will learn how to find all pairs of numbers in a list that add up to a given target sum. This is a common problem in coding interviews and data processing applications. We will iterate through the list, check for pairs that sum to the target value, and store them. This technique is useful in various scenarios, such as detecting complementary values in financial transactions or solving array-based problems efficiently.
# List of numbers
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
target_sum = 10
# List to store pairs
pairs = []
# Finding pairs that sum up to the target
for i in range(len(numbers)):
for j in range(i + 1, len(numbers)): # Avoid duplicate pairs
if numbers[i] + numbers[j] == target_sum:
pairs.append((numbers[i], numbers[j]))
# Output the pairs
print("Pairs with target sum:", pairs)
Pairs with target sum: [(1, 9), (2, 8), (3, 7), (4, 6)]
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
and set the target sum as 10
.i + 1
) to avoid checking the same pair twice.numbers[i] + numbers[j]
equals target_sum
.(numbers[i], numbers[j])
to the pairs
list.i + 1
, we ensure that each pair is checked only once.(9,1)
when (1,9)
is already found.This approach efficiently finds all unique pairs that sum up to the target value. It can be optimized using a set-based lookup to reduce time complexity from O(n2)O(n^2)O(n2) to O(n)O(n)O(n).