[Tutor] IndexError: list index out of range [ Program work fine , but gives this message , guidance requested ]
Guillermo Fernandez Castellanos
guillermo.fernandez.castellanos at gmail.com
Sun Jan 8 13:23:06 CET 2006
Hi,
Look at this:
>>> i=[1,2,3]
>>> i[len(i)]
Traceback (most recent call last):
File "<stdin>", line 1, in ?
IndexError: list index out of range
This means that I have tried to access an element that is out of the
list, in this case i[3], that is, the 4th element of the list.
You are doing the same. You do a
j in range(len(seats))
and then you are accessing your list with seats[j] and seats[j+1]. What
happens when j = len(seats)-1 and you call seats[j+1]? :-)
It happens indeed the same that in the example I gave you first.
Hope it helps. Good luck,
G
John Joseph wrote:
> Hi All
> I am trying to find out the duplicates in a list
> , as for beginning I wanted to compare the adjacent
> elements in list , for this purpose I wrote a script
> for checking the adjacent elements in a list, if same
> , it prints the result that , the adjacent numbers are
> same , it not it will print adjacent numbers are
> same
> My program works , but at the end of
> the program execution it throws error
>
> “Traceback (most recent call last):
> File "arrayduplinital.py", line 27, in ?
> if seats[j] <> seats[j+1]:
> IndexError: list index out of range”
>
> I tried my best to find the logic
> , why this error is coming , I was not able to find
> the reason , I request your guidance for the reason
> for this error and how to avoid it
> I am adding the code which I wrote for
> this program
>
> **************************************************************************************
> """
> find duplicates in a list
> (1) Sort the array
> (2) counter
> i = 0
> j = 0
> (3) for j <= length
> if seats[j] <> seats[j+1] ==> print
> value j and j+1 are not same
> else ===> print value j , j
> +1 are same
>
> """
>
> seats = []
> i = 0
> length = int(raw_input("Enter The Lenght of the array
> : "))
>
> while i < length:
> num = int(raw_input("Enter the Seats : "))
> seats.append(num)
> i += 1
> print seats
>
> seats.sort()
>
> j = 0
> for j in range(length):
> if seats[j] <> seats[j+1]:
> print " The Seat", j , "And the seat",
> j+1 , "value, which are", seats[j]," and", seats[j+1],
> "are not same"
> else:
> print "The Seats ",j ,"And the seats",
> j+1, "Values,", seats[j], "and", seats[j+1], "are
> same"
> ~
>
>
>
>
>
> ___________________________________________________________
> To help you stay safe and secure online, we've developed the all new Yahoo! Security Centre. http://uk.security.yahoo.com
> _______________________________________________
> Tutor maillist - Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
More information about the Tutor
mailing list