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 Collections (2016, retired 2019) Slices Back and Forth

George Lugo
seal-mask
.a{fill-rule:evenodd;}techdegree
George Lugo
Python Web Development Techdegree Student 922 Points

i don't understand what i am doing wrong here

favorite_things = ['raindrops on roses', 'whiskers on kittens', 'bright copper kettles', 'warm woolen mittens', 'bright paper packages tied up with string', 'cream colored ponies', 'crisp apple strudels'] slice1= favorite_things[1:4] slice2 = favorite_things[5:] favorite_things = sorted_things sorted_things.sort()

slices.py
favorite_things = ['raindrops on roses', 'whiskers on kittens', 'bright copper kettles',
                   'warm woolen mittens', 'bright paper packages tied up with string',
                   'cream colored ponies', 'crisp apple strudels']
slice1= favorite_things[1:4]
slice2 = favorite_things[5:]
favorite_things = sorted_things
sorted_things.sort()

1 Answer

The problem is with the last two lines. You should change them to:

sorted_things = favorite_things[:]
sorted_things.sort()

Notice the [:] in front of the favorite_things. This is used to make a copy of favorite_things. If we didn't use that, later when we sort the sorted_things list, it will sort both the sorted_things AND favorite_things! The reason is a little bit complicated, but think of it as this. When we assign sorted_things to favorite_things itself, this is what Python will think:

favorite_things ----------->   ['raindrops on roses', 'whiskers on kittens', 'bright copper kettles', ...]
                                               ^
                    |--------------------------|
sorted_things ------|

As shown, Both the favorite_things and sorted_things are pointing to the same list. So if we change either variable, both of them will be changed. When we make a copy, Python will think this way:

favorite_things -------> ['raindrops on roses', 'whiskers on kittens', 'bright copper kettles', ...]


sorted_things -------> ['raindrops on roses', 'whiskers on kittens', 'bright copper kettles', ...]

I hope this helps. ~Alex

Grigorij Schleifer
Grigorij Schleifer
10,365 Points

This should be marked as the best answer! It really explains the topic!

Thank you :)