You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
The last_index in this code is tracking one position past the last item in the list.
It starts pointing to index 0 in an empty list.
Then, let's say we add 1 to a fresh instance of ArrayList, it will be the only (and also the last) item on index 0, but last_index will be 1
Up to this point, it's not a problem, but could cause problems when trying to pop an item from the list
Let's say we have a list [1,0] with max_size == 2. According to the first snippet, after appending one item last_index == 1. If we insert anything, the first iteration on the loop will try to access the array on index 2, which should cause an IndexError
The text was updated successfully, but these errors were encountered:
classArrayList:
def__init__(self):
self.size_exponent=0self.max_size=0#last_index initialized with -1#could also be useful to check for an empty listself.last_index=-1self.my_array= []
defappend(self, val):
ifself.last_index>self.max_size-1: |\label{line:lst_arr_size}|self.__resize()
#updating last_index prior to appending the itemself.last_index+=1self.my_array[self.last_index] =valdef__resize(self):
new_size=2**self.size_exponentprint("new_size = ", new_size)
new_array= [0] *new_sizeforiinrange(self.max_size): |\label{line:lst_arr_cop1}|new_array[i] =self.my_array[i]
self.max_size=new_sizeself.my_array=new_arrayself.size_exponent+=1definsert(self, idx, val):
#Note the change from > to >=#this is to assure we will not go out of bounds when accessing#last_index+1 to shift the listifself.last_index>=self.max_size-1:
self.__resize()
foriinrange(self.last_index, idx-1, -1): |\label{line:lst_arrlistins_range}|self.my_array[i+1] =self.my_array[i]
self.last_index+=1self.my_array[idx] =val
Chapter 9, Section 2: Python Lists Revisited
The
last_index
in this code is tracking one position past the last item in the list.It starts pointing to index 0 in an empty list.
Then, let's say we add 1 to a fresh instance of
ArrayList
, it will be the only (and also the last) item on index 0, butlast_index
will be 1Up to this point, it's not a problem, but could cause problems when trying to pop an item from the list
But then, there's a problem on this listing:
Let's say we have a list
[1,0]
withmax_size == 2
. According to the first snippet, after appending one itemlast_index == 1
. If we insert anything, the first iteration on the loop will try to access the array on index 2, which should cause anIndexError
The text was updated successfully, but these errors were encountered: