0

Good day everyone,

today I struggled with my code for more than an hour, just to find out that Python did not give an out of bound error. This is my summarised code:

array = []
n = 0
while n < 5:
    array.append(1)
    n = n + 1
print array
for i in range(0,1):
    print i-2
    print array[i-2]

Clearly array[i-2] is out of bound, but the code still runs. This is the output:

[1, 1, 1, 1, 1]
-2
1

Am I missing something, is it my PC or is it something more in depth on how arrays in Python work?

Greetings

Matthias
  • 23
  • 1
  • 4
  • To add some details. What is happening is that the `-2` is not trying to access the `-2` index of the list. Based on the slicing (read the duplicate I linked), you are accessing the second to last item in the list => `[1,2,3,4][-2]` will give you 3 – idjaw Oct 17 '16 at 17:03
  • Detail to keep in mind just for the sake of being complete. In Python an array is not necessarily a list -> http://stackoverflow.com/questions/176011/python-list-vs-array-when-to-use – idjaw Oct 17 '16 at 17:09

2 Answers2

4

You can access Python lists from the end using negative numbers. In the same way some_list[0] gives you the first item in the list, and some_list[1] the second, some_list[-1] will give you the last element on the list, some_list[-2] the second to last, etc.

example = [1, 2, 3, 4]
example[-1] = 4
example[-2] = 3
idjaw
  • 25,487
  • 7
  • 64
  • 83
tomasn4a
  • 575
  • 4
  • 15
1

A note to begin: take care of how you call python lists, because python arrays also exist but they are different objects.

Then you have indeed discovered a property of python list: for your convinience using negative indexes will loop from the end of the list meaning that some_list[-1] is equivalent to some_list[len(some_list)-1].

jadsq
  • 3,033
  • 3
  • 20
  • 32