Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Range isn't matching up with the list

I’m still new to coding and I came across this example. How come the range is 5 and not 6?

NameList=["Olivia", "Madison", "Mia", "Emily", "Charlotte", "Amelia"]

NoMoreSwap=False

while NoMoreSwap==False:
    NoMoreSwap=True
    for Index in range(5):
        if NameList[Index]>NameList[Index+1]:
            Temp=NameList[Index]
            NameList[Index]=NameList[Index+1]
            NameList[Index+1]=Temp
            NoMoreSwap=False


print("The name list is: ", NameList)

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Since you are working with Index index and Index + 1 index you would get out of range since last index 5+1 (for Index in range(6)) is the last one in the loop you asked about.

Your list has 6 values -> len(list)==6 but list[5] is your last index.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading