Indexing array thorough another array

happy new year
my name is frank, I try to display an array thorough another array but I get error message

#import numpy as np
listOfNum1 = [23, 45, 21, 45, 2, 5, 11, 50, 1, 67]
listOfNum2 = [23, 45, 21, 45, 2, 5, 11, 50, 1, 67]
index1 = [1,2,3,4,5,6,7,8,9,10]
index2 = [1,2,3,4,5,6,7,8,9,10]
#arr = np.array([1,2,3,4,5,6,7,8,9,10])
#arrlist1 = np.array([23, 45, 21, 45, 2, 5, 11, 50, 1, 67])
a=0
b=0
sorted(range(len(listOfNum1)), key=lambda k: listOfNum1[k])
print("Elements in the list are : ")
for i in range(len(listOfNum1)):
    print("Element",i," in the list are : ",(listOfNum1[i]))
print("Elements in the list are : ")    
for j in range(len(listOfNum1)):
    for k in range(len(listOfNum1)-1):
        if listOfNum1[k]<listOfNum1[k+1]:
            #a=listOfNum1[k]
            #listOfNum1[k] = listOfNum1[k+1]
            #listOfNum1[k+1]=a
            #a=0
            a=listOfNum1[k]
            listOfNum1[k] = listOfNum1[k+1]
            listOfNum1[k+1]=a
            a=0
            b=index1[k]
            index1[k]=index1[k+1]
            index1[k+1]=b
            b=0
    #print("Element",j," in the list are : ",index1[j],listOfNum1[j])     
print("Elements in the list are : ")            
for j in range(len(listOfNum1)):
    b=index1[j]
    print("Element",j," in the list are : ",index1[j],listOfNum1[j])

print("Elements in the list are : ")            
for j in range(len(listOfNum2)):
    b=index1[j]
    print("Element",j," in the list are : ",b,listOfNum2[b])
   
    

Hello @toronto2009.
Welcome to FCC.
When I run your code on repl.it, I get the following error.

Traceback (most recent call last):
  File "main.py", line 40, in <module>
    print("Element",j," in the list are : ",b,listOfNum2[b])
IndexError: list index out of range

The error is in the last for loop. Try adding the following lines of code just before the last for loop.

print(listOfNum2)   
print(index1) 

Essentially the values of b are the elements of index1 array and you are trying to access listOfNum2[b]) yet some elements of index1 are greater than the index of the last element of listOfNum2. As a result you get the above error. I hope that helps.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.