Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How does a list slice itself?

I am new to python. The code below returns 8. Why?

numbers = [2,3,5,8]
print(numbers[numbers[1]])

When working with slicers, I would expect to see:

print(numbers[:]) = [2,3,5,8]
or 
print(numbers[:-1]) = [2,3,5]

I have never seen something like this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  print(numbers[numbers[1]])

Is the list numbers slicing itself? And if yes, how is it doing it?

>Solution :

What is happening is just nested indexing.
It’s not what you think is happening, instead it’s actually very trivial.

numbers[1] = 3 (for the numbers = [2,3,5,8] )

is acting as an index to the outer one

number[number[1]] = number[3] = 8
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading