Okay, I'm sure this question is a bit trivial, but I'm curious!
In python, it is completely legal to do this:
a = [1,2,3,4,5]
print(a[:123])
>> [1, 2, 3, 4, 5]
but as soon as you try to do this:
a = [1,2,3,4,5]
print(a[123])
>> IndexError: list index out of range
Why is this so, in the context of how it is stored in memory and interpreted by the compiler?
I have tried storing the first example in a variable and checking the length of that variable but it is simply the length of the original list, ignoring the subsequent empty places.
I'm genuinely curious and interested to see what the answers are!
This defines your list with 5 elements
a = [1,2,3,4,5]
This tells you need to start from start to 124th index of the list
>> print(a[:123])
>> [1, 2, 3, 4, 5]
You are right in asking why this does not give a segmentation fault or some memory error as this statement should be illegal. There is no 123rd or 124th index. Python here will start from the beginning and continue iterating until either:-
In other words, If you ask C to walk 123 steps and there is an edge of cliff after 5 steps, C will jump off the cliff but Python will not
In case of
print(a[123])
You are not iterating from start but asking to jump directly to 123rd step. In this case both C and Python will crash with their own cry (IndexError or Segmentation Fault)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With