List Slicing doubt

Hello, everyone! This is a question about list slicing . It seems simple, but i just don’t understand.
When you are slicing a list, why does the final number have to be N+1?

as in:
a_list = [2,4]
but you want the third number on the list as the last one? Im confused about this.

thank you, all in advance!

this is the mission link:
https://app.dataquest.io/m/312/lists-and-for-loops/5/list-slicing

2 Likes

I don’t know if any of this will help you, but it does take a little getting used to at first. I found a thread on Stack Overflow where someone asked this question and people chimed in with responses. You might find the discussion and links interesting (or not!).

I think what helped me to grasp the concept is to keep in mind that indexing is zero-based, so the first element in list has index 0, not 1. You get used to it after a while. I think it’s handy when you have to get the first n elements of a list using a_list[:n], which gives you the items at indices 0, 1, 2, … n-1 for a total of n items.

3 Likes

Thank you! The thread was really helpful!! :grin:

I found this comment especially enlightening.

2 Likes

When slicing, the first argument is the index number. The second is the element number.

For example:

a_list = [2, 4, 6, 8, 10]

There are 5 elements in this list.

If I want to slice the 2nd to 5th elements of this list I would need to perform the below list slice:

print(a_list[1:5]

As you can see, the ‘1’ is the index number and the ‘5’ is the fifth element.

1 Like

A post was split to a new topic: Why is the syntax for selecting the last x elements of a list [-x:] instead of [:-x]?