GitHub Repository Submission

When using GitHub mode, paste your repository URL below and click Save URL to store it. The saved URL will be automatically included with every message you send until you choose to clear it. Learn more

Your GitHub repository URL is saved. LSBot will automatically fetch your latest code from this repository for each message. To change the URL, clear it first and save a new one.

Exercise 2

Can you write some code to change the value 'bye' in the following tuple to 'goodbye'?

stuff = ('hello', 'world', 'bye', 'now')

Note: this problem is a bit tricky.

Solution

Since tuples are immutable, you can't replace 'bye' with 'goodbye'. At best, you can create a new tuple and reassign it:

stuff = ('hello', 'world', 'goodbye', 'now')
stuff = stuff[0:2] + ('goodbye', stuff[3])
stuff = list(stuff)
stuff[2] = 'goodbye'
stuff = tuple(stuff)

Solution 1 creates an entirely new tuple with the changed value. That's not quite in the spirit of what we're asking. It would also be tedious if the tuple contained more than a few elements.

Solution 2 is a little closer to being in the proper spirit. This one concatenates a slice of the original tuple combined with a new tuple that includes 'goodbye' and 'now' (from stuff[3]). However, that code is difficult to read. Furthermore, the slicing and indexing is a sure-fire way to get an off-by-one error. For example, if you wrote stuff[0:1] instead of stuff[0:2], the result would be missing 'world'.

Solution 3 is as close as we can get to the spirit of the problem. Here, we convert the original tuple to a list and reassign the element to the new value. Finally, we transform the list into a new tuple. This approach still creates an entirely new tuple. However, it avoids the problem of re-entering a long list of members, is cleaner than slicing and indexing, and is much easier to read.

Video Walkthrough

Hi! I'm LSBot. I can help you think through the selected exercise by giving you hints and guidance without revealing the solution. Your code from the editor will be automatically detected. Want to know more? Refer to the LSBot User Guide .

Detected solution
Loading...

Submit your solution for LSBot review.

Hi! I'm LSBot. Your code from the editor will be automatically detected. I'll review your solution and provide feedback to help you improve. Ask questions about your solution or request a comprehensive code review. Want to know more? Refer to the LSBot User Guide .

Detected solution
Loading...