Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is it that you can slice a list past the total index count, but you cant directly retrieve said index? [duplicate]

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!

like image 825
ZionEnglish Avatar asked Nov 01 '25 04:11

ZionEnglish


1 Answers

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:-

  1. Maximum index (123) is reached OR
  2. List items run out

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)

like image 87
satyakam shashwat Avatar answered Nov 02 '25 19:11

satyakam shashwat