Slicing with "len()"?

In this exercise on string slicing, we are asked to write a function that concatenates the last three letters of two different strings and returns them as a new string. Here is a screenshot of the instructions:

I learned how to slice lists before this exercise and I’ve learned how to use the len() function before this exercise, and it doesn’t seem like slicing strings is all that different from slicing lists. I could be wrong, so please correct me if I am!

My question is this - why is the len() function necessary for this exercise? In the hint in the screenshot, you can see that they suggest using the following code:


However, here is the code I wrote for this exercise:

new_string = first_name[-3:] + last_name[-3:]

Why is the len() function necessary in this instance? I understand this particular lesson is discussing this function, but it just appears to be absolutely pointless to use it in this exercise. Am I missing something here?

1 Like

Hello, @okaraman7.

As the hint states, “we could use len:”
You’ve shown that we obviously don’t have to use len. I think the exercise is leading up to how to use negative indices, which you clearly understand already. The next exercise shows that using len is not necessary. :wink:

Happy coding!

1 Like

@midlindner I was just editing my post when you responded!! :grin: The next exercise clearly states that using negative indices is an easier way to do this. I guess I’m still a little baffled as to why they would use len() to slice when they’re going to introduce an easier way to slice in the next lesson (negative indices). It also seems a little odd that they do this given that we’ve already learned how to use len() and how to slice…but I’m glad to know that I’m not missing anything, at least!

1 Like

Slicing uses the same operator as indexing, [] which corresponds to __getitem__:

class Thing:
    def __getitem__(self, key):

Thing()[slice(3, 5, None)]
Thing()[slice(3, None, None)]

It’s then up to the object in question to decide how it responds to that request, and yes, strings and lists behave largely the same and presumably a couple other things also respond to this.

1 Like