Why does new_word know how long it is


#1

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

Hello. I'm not necessarily stuck, just confused.

new_word=word[1:len(new_word)]

Why does this work? How does new_word know how long it is before it has actually been told exactly which characters from the string variable "word" are being allocated to it? Should it be like this?:

new_word=word[1:len(word)]

Thanks for any help. I really want to understand this before moving forward.


#2

It doesn't. That line will throw an error.

new_word = word + first + pyg

Now we've defined the string, and can write,

new_word = new_word[1:len(new_word)]

#3

But you assign new_word on this line, how does it know the length of new_word then? That is the question


#4

It knows from this,

new_word = word + first + pyg

#5

ofc, silly me. Thank you mtf


#6

This screenshot shows it working.


#7

Working in the sense that it passes you.

It doesn't do what it should. Refresh page and run it again.


#8

All right, now it throws an error. But why didn't it do that the first time? As you can see from the output in the screenshot I provided it ran fine :confused:


#9

Refreshing the page has the effect of giving you a new instance of a Python interpreter which means that everything you had defined earlier is now gone.

Your code was relying on such a value, using something it did not define.


#10

aaaaand my brain isn't scrambled egg any more. Thanks, bro!


#11

Further, the way you would express "all but the first" is:

sequence[1:]

Left out parameters are given default values. [:] for example, creates a copy.


#12

Which is true, but not what the instructions ask for. The above longer expression is what is in the instructions.