Python Code Example: Prints out Indices of all Pairs of Numbers

In this Python tutorial, we will learn how to find and print out the indices of all pairs of numbers in a list. A pair consists of two numbers, and we will generate all possible combinations of pairs in the list, then print their indices. This can be useful in scenarios like finding matching elements or working with pairs in algorithms, where knowing the positions of elements is crucial. We will use nested loops to achieve this.

Code Example

# List of numbers
numbers = [10, 20, 30, 40, 50]

# Loop to print out indices of all pairs
for i in range(len(numbers)):
    for j in range(i + 1, len(numbers)):  # Ensure no repeating pairs
        print(f"Pair: ({numbers[i]}, {numbers[j]}) - Indices: ({i}, {j})")

Output

Pair: (10, 20) - Indices: (0, 1)
Pair: (10, 30) - Indices: (0, 2)
Pair: (10, 40) - Indices: (0, 3)
Pair: (10, 50) - Indices: (0, 4)
Pair: (20, 30) - Indices: (1, 2)
Pair: (20, 40) - Indices: (1, 3)
Pair: (20, 50) - Indices: (1, 4)
Pair: (30, 40) - Indices: (2, 3)
Pair: (30, 50) - Indices: (2, 4)
Pair: (40, 50) - Indices: (3, 4)

Code Explanation

  1. List of Numbers: We define the list numbers = [10, 20, 30, 40, 50], which contains the numbers we will pair up.
  2. Nested Loops:
    • The outer loop (for i in range(len(numbers))) iterates through each element in the list.
    • The inner loop (for j in range(i + 1, len(numbers))) ensures that we only consider pairs where the second number in the pair is after the first number in the list. This prevents repetition of pairs (like (10, 20) and (20, 10)).
  3. Printing the Pair and Indices: Inside the inner loop, we print the current pair of numbers (numbers[i] and numbers[j]) along with their corresponding indices (i and j).
  4. Output: The program prints all unique pairs of numbers from the list along with their indices.

This code demonstrates how to generate all unique pairs of numbers in a list and print both the numbers and their indices. It’s a useful technique in problems involving pairwise comparisons or processing pairs of items.