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

Calling .sort() method after creating a copy of a list using [:] in Python

I know that I can break sorted_things=favorite_things[:].sort() into 2 steps to make it pass the test:

sorted_things = favorite_things[:] sorted_things.sort()

However, why does doing both steps at once using sorted_things=favorite_things[:].sort() result in an empty list?

Any help would be much appreciated!

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:]
sorted_things=favorite_things[:].sort()

1 Answer

This is because .sort() sorts a variable in place, and there's another function called sorted() that just sorts a list without changing the variable in place. For example; in this code both a and b will be the list [1, 2, 3, 4, 5].

mixed = [3, 4, 2, 5, 1]

a = sorted(mixed)  # sorted() doesn't change a variable; it just returns the sorted version of a list

b = mixed[:]
b.sort()   # .sort() changes a variable in place, and returns nothing

# Both a and b are the same list, and the mixed list didn't change

sorted_things = favorite_things[:].sort()  # Remember, .sort() returns nothing, so sorted_things will be None

:point_right: I think the challenge is expecting you to use .sort().

I hope you get it. ~Alex

Ah, I see! Thanks for reminding me that .sort() returns nothing!

No problem :)