The check function has two parameters: param - the number of elements in the list and num - the list itself. First, we check whether the number of specified elements in the list matches the number that was entered by the user. Next, I have the following task: I have to see if there are identical elements in the list and delete one of them. I get the error IndexError: list index out of range in line 13. Help please, it is very necessary. Thank!

def check(param, num): if (param != len(num)): print(param) print(len(num)) return False else: a = len(num) for i in range(a): for j in range(a): if (i == j): continue else: if (num[i] == num[j]): num.pop(j) return num c = 9 d = [2, 1, 3, 2, 9, 1, 2, 3, 1] print(check(c, d)) 
  • one
    What should the program display? - Andrey
  • I have already edited the program. It should return a list in which there are no identical elements if the previous condition is met. - Ram Kudusov
  • If the number of items in the list corresponds to the stated? - Andrey
  • This is followed by the next branch of the function in which the deletion of identical elements in the list is assumed. - Ram Kudusov

1 answer 1

Error in this block:

 a = len(num) for i in range(a): for j in range(a): if (i == j): continue else: if (num[i] == num[j]): num.pop(j) 

The fact is that after num.pop(j) , which removes elements from the list, the number of elements in the list decreases and the variable a does not change, so there will come a moment when the value of j or i in the cycle exceeds the number of elements present in the list .

As it seems to me, the solution might look like this:

 def check(param, num): if len(num) == param: return list(sorted(set(num), key=lambda s: num.index(s))) else: print('Заявленное количество элементов %s\n' 'не соответвует реальному %s' % (param, len(num))) return False 

Solution via loop (with output formatting did not bother):

 def check(param: int, num: list): if param == len(num): for _ in range(len(num)): for j in range(len(num)): if num.count(num[j]) > 1: num.pop(j) break print(num) return True else: return False 
  • Yes, I realized that there was an error in this block, I even indicated a line. I have already been helped, thank you for the answer. - Ram Kudusov
  • Thank you for your answer, it suits me too) - Rem Kudusov