Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Python Basics (Retired) Shopping List Lists and Strings

I'm stuck on how to replace single items within a list with others without a big workaround.

I'm having an issue on Challenge task 3 of 3 where I just don't understand how to replace single list items from one list to another...

Cody Te Awa
Cody Te Awa
8,820 Points

Hi, could you give an example of exactly what you mean?

3 Answers

Sreng Hong
Sreng Hong
15,083 Points

To replace the list item:

You should point to the index of that item and then assign it to another item that you want.

For example if you want to replace letter 'c' to 'd':

list = ['a', 'b', 'c']

list[len(list)-1] = 'd'

or

list[-1] = 'd'

By the way, Fabion already gave you the correct answer to pass the challenge.

Take a look at this:

full_name = "Fabion Stephens"
name_list = full_name.split()
greeting_list = "Hi, I'm X".split()
greeting_list[-1] = name_list[0] # <-- this is how you would replace the last item in the list 
greeting = ' '.join(greeting_list) # <-- then make it a sentence again using the join method with the list as its param

Thank you both! I would've preferred the answer that Sreng gave me so that I can try again on my own, but it's good to see the full thing worked out with comments! :)