def Task4():
import random
t = True
list1 = []
list2 = []
rand = random.randint(1,6)
list1.append(rand)
print(list1)
for x in range(0,5):
if list1[0] == (rand):
list1.pop(0)
else:
list2.append(rand)
print(list2)
list1.pop(0)
Can't workout why if list1[0] == (rand)
: keeps coming up with a list index out of range.
3 Answers 3
Let’s see what happens to list1
:
list1 = []
Ok, the list is created, and it’s empty.
rand = random.randint(1,6)
list1.append(rand)
rand
is added to the list, so at this point list1 = [rand]
.
for x in range(0,5):
This will loop four times; so let’s take a look at the first iteration:
if list1[0] == (rand):
Since list1 = [rand]
, list1[0]
is rand
. So this condition is true.
list1.pop(0)
The list element at index 0 is removed; since list1
only contained one element (rand
), it’s now empty again.
for x in range(0,5):
Second iteration of the loop, x
is 1
.
if list1[0] == (rand):
list1
is still empty, so there is no index 0
in the list. So this crashes with an exception.
At this point, I would really like to tell you how to solve the task in a better way, but you didn’t specify what you are trying to do, so I can only give you a hint:
When you remove items from a list, only iterate for as often as the list contains elements. You can either do that using a while len(list1)
loop (which will loop until the list is empty), or by explicitely looping over the indexes for i in len(list1)
. Of course, you can also avoid removing elements from the list and just loop over the items directly using for x in list1
.
Comments
when x is 0: -> you pop the only existing list item, thus the list is empty afterwards
when x is 1: -> you try to access list1[0], which doesn't exist -> list index out of range error
2 Comments
truth is evident with debugging with print and try except:
def Task4():
import random
t = True
list1 = []
list2 = []
rand = random.randint(1,6)
list1.append(rand)
for x in range(0,5):
try:
print("list1 before if and pop",list1)
if list1[0] == (rand):
list1.pop(0)
print("list1 after pop",list1)
else:
list2.append(rand)
print("list2 {}".format(list2))
list1.pop(0)
except IndexError as e:
print("Index Error {}".format(e))
break
Task4()
list1 before if and pop [3]
list1 after pop []
list1 before if and pop []
Index Error list index out of range
if list1 and list1[0] == rand