2

i wrote this program :

l = []
N = int(input("enter the size of the list"))
if N < 50:
  for i in range(N):
      a = int(input("add a number to the list"))
      l.append(a)
  for i in range(N):
      del l[min(l)]
      print(l)

and when i run it they say

Traceback (most recent call last): 
File "<pyshell#5>", line 2, in <module> 
del l[min(l)]  
IndexError: list assignment index out of range

please do you have any solutions ??

2
  • 3
    What do you precisely want to do at this step del l[min(l)] ? Consider a list [10, 20, 30] now image the execution of del l[min(l)]. This would be del l[10], but there is not 10th element in the list and hence shows error Commented Mar 8, 2017 at 18:48
  • 1
    Suppose l is [23, 42, 99]. Then del l[min(l)] is equivalent to del l[23], which is equivalent to "delete the 24th element of l". But l doesn't have 24 elements, it has three elements. Commented Mar 8, 2017 at 18:49

2 Answers 2

2

Your problem is that del l[min(l)] is trying to reference the list item at index min(l). Let's assume that your list has 3 items in it:

l = [22,31,17]

Trying to delete the item at the index min(l) is referencing the index 17, which doesn't exist. Only indices 0, 1, and 2 exist.

I think what you want to do is remove the smallest item from your list sequentially. There are a number of ways to do this. The method that is closest to what you have written would be:

for i in range(N):
    l.remove(min(l))
    print(l)
Sign up to request clarification or add additional context in comments.

Comments

2

Change

del l[min(l)]

to

del l[l.index(min(l))]

Reason : Because you want to delete element holding index of min element and not index=min element

O/P : (for input 1 2 3 4 5)

[2, 3, 4, 5]

[3, 4, 5]

[4, 5]

[5]

[]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.