Python Practice › List Programs › Program 8

Pairs whose sum is 10

MediumList Programs · 8 of 100

Write a Python program to print every pair of elements from a list whose sum is 10.

Advertisement
Input
[2, 8, 5, 3, 7, 5, 1]
Output
[(2, 8), (5, 5), (3, 7)]

Approach

  1. Check every pair (i, j) with j after i so no pair is repeated.

Solution

Python
numbers = [2, 8, 5, 3, 7, 5, 1]pairs = []for i in range(len(numbers)):    for j in range(i + 1, len(numbers)):        if numbers[i] + numbers[j] == 10:            pairs.append((numbers[i], numbers[j]))print(pairs)
Output
[(2, 8), (5, 5), (3, 7)]

Line by line

Line 4

Starting the inner loop at i + 1 avoids pairing an item with itself or counting a pair twice.

Learn the concept

New to this topic? Read the lesson, then come back.

More list programs

← All 100 List Programs

Leave a Comment