This is a list problem question. if list[j]==list[j+1]: IndexError: list index out of range

Asked 2 years ago, Updated 2 years ago, 45 views

A 'run' is a sequence in which the same value is repeated. Write a program that calculates the longest run from the following list. For example, the length of the longest run in the list with the following elements is 4.

[1,2,5,5,3,1,2,4,3,2,2,2,2,3,6,5,5,6,3,1]

in question
if list[j]==list[j+1]: IndexError: list index out of range Which part should I correct? I don't know much about Python beginners.

run=[1,2,5,5,3,1,2,4,3,2,2,2,2,3,6,5,5,6,3,1] 
list =[]
for i in run:
  a=1
  list.append(a)
  for j in list:
    if list[j]==list[j+1]:
      len(list)
    else:
      list.clear()
  print(a)

Image

list python

2022-09-20 17:40

1 Answers

For example, if the list length is 8 (i.e., if there are only 8 numbers),

if list[7] == list[7 + 1] is executed when checking for the last 8th number.

If you think carefully, list[8] is a number that does not exist. (It means the ninth number.))

It's an error that everyone makes at least once.

list[j + 1] exists and you can check if the value is the same as something else.

+ let's make a name like number = [].


2022-09-20 17:40

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.