Indexing Confusion


#1

I actually posted this question a while back and did not get a great response. I am having trouble understanding how python labels the items in an index. This is my code:

suitcase =['sunglasses', 'hat', 'passport', 'laptop', 'suit', 'shoes']

first = suitcase[0:2]   # The first and second items (index zero and one)
middle = suitcase[2:4]   # Third and fourth items (index two and three)
last = suitcase[4:6]     # The last two items (index four and five)
print(first)
print(middle)
print(last)

It works, but I don't get it. (I added the print part just to verify results in PyCharm.) Given that code, this is how the lists have been assigned:

sunglasses is assigned [0]
hat is assigned [2]
passport is also assigned [2]
laptop is assigned [4]
suit is also assigned [4]
shoes is assigned [6]

I would have expected each of the items to have a consistent index value. What is going on? Again, I know how to get the right answer for this lesson, I just don't understand why python seems to have inconsistent indexing. Also, what is the rationale behind this unique indexing system in python? (It is different than other programming languages.) Anybody know?

Thanks!


#2

Hi!

Let's take a look at the output for your print statements and see what's going on here. When I put the code into the CodeAcademy interpreter, here is the output:

['sunglasses', 'hat'] #first = [0:2]
['passport', 'laptop'] #middle = [2:4]
['suit', 'shoes'] #last = [4:6]

Remember, as you pointed out, the start index in list slicing is the same as the first parameter's value, and the stop index is one less than the actual parameter's value.

Just to make sure this is the case, let's put all of the members back into the list and see what happens:

new_list = []

for i in first:
    new_list.append(i)
for j in middle:
    new_list.append(j)
for k in last:
    new_list.append(k)

print new_list
---
Output:
['sunglasses', 'hat', 'passport', 'laptop', 'suit', 'shoes']

We can see that sunglasses is assigned [0], hat is assigned [1], and so on.

Your confusion seems to be coming from the notation; remember that [0:2] signifies indexes 0 and 1, while [2:4] signifies indexes 2 and 3. So, no items should overlap in index assignments.


The method of using 0-base indexing is common to many languages, with C being the forerunner of this technique. In my opinion, although it takes time to get used to, having the assignment [start(index):stop(index-1)] helps with keeping track of list slicing. For example, if I stop at [0:2], I know the next one should start [2:...].

Hope this helps!


#3

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.