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

In this code example all pairs of numbers in a list are recognized and output with indication of the position.

Code Explanation

LineDescription
1Function header of the function getPairs() which expects a list as parameter.
2For loop to go through all list items. The range is 0 to length of the list.
3For loop to loop through all list elements to check if there are double values in the list. The range is i – 1 to length of the list.
4Check if there are duplicate values.
5 – 8prints all duplicate values with their indexes
11Declaration and initialization of the list myList with the values 1, 3, 4, 6, 1, 9, 4, 8 and 9
12Calls the function getPairs(myList)
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