Why does the len() function return 7 instead of 8 in this case


#1


https://www.codecademy.com/courses/python-beginner-2W5v7/1/5?curriculum_id=4f89dab3d788890003000096


I input a word 'pcman'
Therefore, I got 'pcmanpay' as my new_word.
I don't get why it is new_word[1:len(new_word)] instead of new_word[1:len(new_word)-1] as the final output since 'pcmanpay' has 8 letters and the len() should return 8.
I know that len() returns 7 after testing but I wanna know why.


pyg = 'ay'

original = raw_input('Enter a word:')

if len(original) > 0 and original.isalpha():
    word = original.lower()
    first = word[0]
    new_word = word + first + pyg
    new_word = new_word[1:len(new_word)]
    print new_word
else:
    print 'empty'


#2

The length is 8 at that point (line 9) when the input is 'pcman', and that is what len will return.

Your print will output 7, because at that point, the length is 7.

The length changed, that's what line 9 does, it removes a character.


#3

Sorry for the confusion
I accidentally pasted the code I used for testing
What I want to know is that the final output should contain letters [1] to [len() - 1].
I don't see why len() works in this case


#4

Well, which indexes should be included and what should the begin/end values be to get those indexes?

The arguments for slicing match that of
https://docs.python.org/2/library/functions.html#range


#5

I'm thinking every letter except new_word[0], so new_word[1], new_word[2], new_word[3], new_word[4], new_word[5], new_word[6], new_word[7] should be included.

0
p

1-2-3-4-5-6-7
c-m-a-n-p-a-y respectively

I still dont see why it's from index 1 to index 8 instead of from index 1 to index 7


#6

>>> range(1, 8)
[1, 2, 3, 4, 5, 6, 7]

from help(range):

For example, range(4) returns [0, 1, 2, 3]. The end point is omitted!

That's not to say that all functions etc match up in that way but here they do and.. documentation for slicing is a little harder to find :S


#7

So.... technically string[start : stop] would return letters from index (start) to index (stop - 1).

Does an array in python do the same thing? :c


#8

strings and lists are both sequences and slicing behaves the same for all sequences, yes.

https://docs.python.org/3/library/stdtypes.html#common-sequence-operations


#9

THANK YOU !!!!!