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 trialMarco Koopman
5,290 PointsWhy does sorted_things.sort() acts differently when you add [:] behind it
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']
sorted_things = favorite_things[:]
sorted_things.sort()
slice1 = favorite_things[1:4] slice2 = favorite_things[5:]
print(sorted_things) print(favorite_things)
Acts like it should but when I change:
sorted_things = favorite_things[:] to sorted_things = favorite_things
It changes favorite things too when I sort sorted_things.
Is this supposed to happen? And why does this happen?
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
sorted_things.sort()
2 Answers
Alexander Davison
65,469 Points.sort()
is designed to sort the list in place. Therefore, if you call .sort()
on a list, it modified the list. Sometimes you don't want to sort it in-place so therefore you use the sorted
function.
>>> my_list = [2, 1, 3]
>>> my_list
[2, 1, 3]
>>> sorted(my_list)
[1, 2, 3]
>>> my_list
[2, 1, 3]
>>> my_list.sort()
>>> my_list
[1, 2, 3]
Kai Page
4,406 PointsI'm having this exact same issue. Do we know why?
Marco Koopman
5,290 PointsMarco Koopman
5,290 PointsHey, Thanks for the aswer but this is not what I meant.
I was wondering why .sort() effects both favorite_things as sorted_things when I only sort sorted_things.
But when I write the variable value like this: favorite_things[:] It only changes sorted_things.
.sort() shouldn't have any effect on favorite_things because I never use this function on this variable.