Python Program to Find Pairs with a Given Sum
Intermediate · Lists
This program finds every pair of numbers in a list that add up to a target, for example the pairs that make 11. It is a classic interview question, often called the two sum problem. The main program checks every pair with two loops, and the alternatives show faster methods.
Program
List: [2, 7, 4, 5, 9, 1, 6] Pairs that add up to 11: 2 + 9 = 11 7 + 4 = 11 5 + 6 = 11 Pairs found: 3
How it works
- The outer loop picks the first number of a pair, and the inner loop picks the second.
- The inner loop starts at
i + 1, so a number is never paired with itself and the same pair is never printed twice, as 2 + 9 and 9 + 2. - Every pair whose sum equals
targetis printed and counted. - Checking every pair takes about n x n / 2 steps, which is fine for short lists but slow for long ones.
Other ways to write it
One pass with a set
7 + 4 = 11 2 + 9 = 11 5 + 6 = 11
For each number, the program asks whether its partner has already been seen. A set answers that quickly, so the list is read only once.
Two pointers on a sorted list
Sorted list: [1, 2, 4, 5, 6, 7, 9] 2 + 9 = 11 4 + 7 = 11 5 + 6 = 11
After sorting, one pointer starts at each end. A sum that is too small moves the left pointer up, and a sum that is too big moves the right pointer down.
Try it yourself
Set target to 20 to see the "No pairs found" message.
Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.
Related programs
- Find Common Elements in Two Lists
- Find the Missing Number in a List
- Binary Search
- Find Pythagorean Triplets
- Find the Largest and Smallest Number in a List
- Swap Elements at Even and Odd Positions in a List
- Find the Second Largest Number in a List
- Remove Duplicates from a List
- a Menu-Driven List
- Find the Sum of Elements in a List
All Python programs · CBSE class 12 practical file · Python exercises