Python Code Example: prints out indices of all pairs of numbers

This code is a function named “getPairs” which takes a list as an input and outputs the pairs of duplicated elements in the list.

  1. The function uses two nested for loops. The outer loop iterates through each element of the list, and the inner loop starts from the next element of the outer loop and iterates till the end of the list.
  2. In the inner loop, the code checks if the current element of the outer loop is equal to the current element of the inner loop. If the elements are equal, this means that there is a duplicate in the list.
  3. The code then prints the message “Number ” + str(myList[i]) + ” is included two times, at indices ” + str(i) + ” and ” + str(j)) to inform the user about the duplicated elements.
  4. Finally, the function is called by passing the list myList as an argument. The code will output the pairs of duplicated elements in the list.
def getPairs(myList):
    for i in range(0, len(myList)):
        for j in range(i + 1, len(myList)):
            if (myList[i] == myList[j]):
                print(
                    "Number " + str(myList[i]) +
                    " is included two times, at indices " +
                    str(i) + " and " + str(j))


myList = [1, 3, 4, 6, 1, 9, 4, 8, 9]
getPairs(myList)
Output
Number 1 is included two times, at indices 0 and 4
Number 4 is included two times, at indices 2 and 6
Number 9 is included two times, at indices 5 and 8