Home > Net >  Get the index of the 5 biggest values in a list
Get the index of the 5 biggest values in a list

Time:11-12

Currently working on a list, and I have to try to get the 5 largest numbers and their indexes. But for some reason, when I run what I thought would give me the 5 largest numbers and their indexes it is not saving the information as I expected it. Here is my code:

# Given list
list = [13, 11, 12, 11, 8, 8, 10, 8, 9, 12, 10, 10, 11, 13, 9, 8, 8, 8, 9, 11, 6, 3, 6, 7, 3, 11, 9, 10, 2, 9, 4, 11]

# Created a temporary list so that I can modify it as I please and a new list to store the index of the largest numbers
templist = list
largest = []

# For loop to iterate 5 times
for x in range(5):
  index = templist.index(max(templist))
  largest.append(index)
  templist.pop(index)
  templist.insert(index, 0)
  # Added the last to lines to remove the largest number taken and replace it with a 0 so once it iterates again it does not get the same number

print(largest)
print(templist)
print(list)
# At this point, when printing the original list, it seems like the data stored on the templist is being written on the original list since when I print this it is giving me the output:
# [0, 13, 2, 9, 1]
# [0, 0, 0, 11, 8, 8, 10, 8, 9, 0, 10, 10, 11, 0, 9, 8, 8, 8, 9, 11, 6, 3, 6, 7, 3, 11, 9, 10, 2, 9, 4, 11]
# [0, 0, 0, 11, 8, 8, 10, 8, 9, 0, 10, 10, 11, 0, 9, 8, 8, 8, 9, 11, 6, 3, 6, 7, 3, 11, 9, 10, 2, 9, 4, 11]

Any idea why it is rewriting the original list aswell?

CodePudding user response:

Here's a modified version of your code that will give you something closer to what you expected, with explanations in line of the changes I've made.

# First off, "list" is a special name in Python and represents the "type" list. 
# Therefore it's best not to use "list" as a variable name. Suggest "list1" instead:
list1 = [13, 11, 12, 11, 8, 8, 10, 8, 9, 12, 10, 10, 11, 13, 9, 8, 8, 8, 9, 11, 6, 3, 6, 7, 3, 11, 9, 10, 2, 9, 4, 11]


# If you wish to make a copy of something to manipulate while retaining the original,
# it's best to use copy(), as below. 
# If you simply say "templist = list1", you're essentially creating two different
# names by which to refer to the same object - mutating one will mutate the other. 
templist = list1.copy()
largest = []

# For loop to iterate 5 times
for x in range(5):
  index = templist.index(max(templist))
  largest.append(index)
  
  # Instead of these two lines...
  
  # templist.pop(index)
  # templist.insert(index, 0)
  
  # you can just do this.
  templist[index] = 0
  
  

print(largest)
print(templist)

for i in largest:
    print (i, list1[i])
    
# Result: 
    # 0 13
    # 13 13
    # 2 12
    # 9 12
    # 1 11
  • Related