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!

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


Idan Bar-Dov
Idan Bar-Dov
1,371 Points

slice without parameters vs. equal

Around 5:47, Kenneth creates a copy of messy_list by using slice, as follows: clean_list = messy_list[:]

What is the purpose of using slice here? dropping the slice part, as follows, seems cleaner. clean_list = messy_list

1 Answer

Cheo R
Cheo R
37,150 Points

Take a look at:

lst = list(range(50))
also_lst = lst
new_lst = lst[:]

print("lst id: ", id(lst))                   # lst id:       139777404330952
print("also_lst id: ", id(also_lst))  # also_lst id:  139777404330952

print("new_lst: ", id(new_lst))      # new_lst:  139777411441160

print(also_lst is lst)                       # True
print(new_lst is lst)                       # False

Where the former assigns to variables to the same object (they both point to lst). The latter is assigned (points to) a new list (copied). The is operator tests if two variables point the same object, not if two variables have the same value