0

I'm trying to make a list of 11 elements

I want to pop out the maximum element only from l[0] to l[5]. under one of the two conditions:

l[5] >= 3 or l[5] is no longer exist or None.

l = [2,8,6,2,8,7,9,8,6,7,4]
max = 0
maxIndex = 0
while (l[5] >= 3 or l[5] is None):
    for x in range(6):
        if l[x] > max:
            max = l[x]
            maxIndex = x
    l.pop(maxIndex)
print(l)

I am getting the error:

IndexError: list index out of range

I know at some point l[5] will no longer exist, but how can I create this code.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Xi N
  • 1
  • 2
  • Add a condition in the while statement which should go first. It should be: `len(l) > 5` – sshashank124 Apr 20 '15 at 20:34
  • 1
    Your function is rather complex; all you really need is [`heapq.nsmallest()`](https://docs.python.org/2/library/heapq.html#heapq.nsmallest) here. – Martijn Pieters Apr 20 '15 at 20:50
  • You want the **top-n (here, n=6), subject to the condition that x >= 3**. As @MartijnPieters said, don't start from a list in the first place, use a self-sorting data structure like `heapq` – smci Apr 20 '15 at 20:58
  • Don't say *"pop... from a list"*. Say *"Get top-n"*. State your problem without nailing it down to specific data structures or operations. – smci Apr 20 '15 at 21:00

3 Answers3

2

Minimal reproducible code:

l = [1, 2, 3]
l[3] is None # raises IndexError
assert len(l) == 3 # len(l) returns 3

As you can see, accessing non-existing item raises an IndexError, so correct condition should contain length test.

while (len(l) >= 6 and l[5] >= 3):
Łukasz Rogalski
  • 22,092
  • 8
  • 59
  • 93
0

Reverse the conditions:

l = [2,8,6,2,8,7,9,8,6,7,4]
max = 0
maxIndex = 0
while len(l) > 5 or l[5] >= 3:
    for x in range(6):
        if l[x] > max:
            max = l[x]
            maxIndex = x
    l.pop(maxIndex)
print(l)
sshashank124
  • 31,495
  • 9
  • 67
  • 76
hd1
  • 33,938
  • 5
  • 80
  • 91
0

I think this does all you need - returns maximum if there is a 5th element and it's >=3 or None

>>> l =  [2,8,6,2,8,7,9,8,6,7,4]

>>> max(l[0:5]) if len(l)>5 and (l[5]>=3 or l[5] is None) else None
8

>>> l = [1,2,3]
>>> max(l[0:5]) if len(l)>5 and (l[5]>=3 or l[5] is None) else None
>>>
emvee
  • 4,371
  • 23
  • 23