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

How do you swap the value between two lists?

Stuck in this part of the "Challenge Task". I am not sure what is it asking. What would be the best way to approach this situation.

greeting_list.py
full_name = "Joa Angelo"
name_list = full_name.split()
greeting = "Hi, I'm Treehouse"
greeting_list = greeting.split()

1 Answer

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,423 Points

Instead of swapping, the challenge is asking to replace an item in one list with the value of a second list. The second list is unchanged, so "swapping" isn't precisely the correct work. (coders tend to be overly precise!)

To replace the third (or 2nd-index) item in greeting_list with the first (or 0th-index) item in name_list use:

greeting_list[2] = name_list[0]

Advanced feature: If you truly wanted to swap them you could use the tuple pack/unpack method you'll see later in the course:

greeting_list[2], name_list[0] = name_list[0], greeting_list[2]

This forms a tuple of the original values on the right-side of the equals sign, then unpacks these values into the variables on the left-side of the equals sign. It's the comma that makes the tuples happen. This is equivalent to:

greeting_list[2], name_list[0] = (name_list[0], greeting_list[2])

The parens are optional.