Find All Pairs with Given Sum in List in Python - Simple Guide
To find all pairs in a list that add up to a given sum in Python, you can use a loop with a set to track seen numbers and check if the complement (sum minus current number) exists. Use
for loops and a set to efficiently find pairs without duplicates.Syntax
Use a loop to go through each number in the list. For each number, calculate the complement by subtracting it from the target sum. Check if this complement is already in a set of seen numbers. If yes, you found a pair. Add the current number to the set for future checks.
python
def find_pairs_with_sum(numbers, target_sum): seen = set() pairs = [] for num in numbers: complement = target_sum - num if complement in seen: pairs.append((complement, num)) seen.add(num) return pairs
Example
This example shows how to find all pairs in a list that add up to 10. It prints each pair found.
python
def find_pairs_with_sum(numbers, target_sum): seen = set() pairs = [] for num in numbers: complement = target_sum - num if complement in seen: pairs.append((complement, num)) seen.add(num) return pairs numbers = [2, 4, 3, 5, 7, 8, 9] target_sum = 10 pairs = find_pairs_with_sum(numbers, target_sum) for pair in pairs: print(pair)
Output
(3, 7)
(2, 8)
Common Pitfalls
One common mistake is counting the same pair twice, like (3,7) and (7,3). Using a set to track seen numbers helps avoid this. Another mistake is not handling duplicates in the list properly, which can cause repeated pairs.
Also, using nested loops to check every pair works but is slower for large lists.
python
def wrong_find_pairs(numbers, target_sum): pairs = [] for i in range(len(numbers)): for j in range(i + 1, len(numbers)): if numbers[i] + numbers[j] == target_sum: pairs.append((numbers[i], numbers[j])) return pairs # This works but is slower and can be inefficient for big lists # Correct approach uses a set to track seen numbers and avoid duplicates
Quick Reference
- Use a
setto track numbers seen so far. - Calculate complement as
target_sum - current_number. - Add pairs only when complement is found in the set.
- This method runs in O(n) time, better than nested loops.
Key Takeaways
Use a set to track seen numbers for efficient pair finding.
Calculate complement as target sum minus current number to find pairs.
Avoid nested loops for better performance on large lists.
Watch out for duplicate pairs by controlling order and storage.
Return pairs as tuples for clear and simple output.