In this code example all pairs of numbers in a list are recognized and output with indication of the position.
Line | Description |
---|---|
1 | Function header of the function getPairs() which expects a list as parameter. |
2 | For loop to go through all list items. The range is 0 to length of the list. |
3 | For 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. |
4 | Check if there are duplicate values. |
5 – 8 | prints all duplicate values with their indexes |
11 | Declaration and initialization of the list myList with the values 1, 3, 4, 6, 1, 9, 4, 8 and 9 |
12 | Calls 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)
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