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 Introduction To Slices

Pei Sheng Tan
seal-mask
.a{fill-rule:evenodd;}techdegree
Pei Sheng Tan
Python Web Development Techdegree Student 2,600 Points

What's the difference between using slice to create a copy, and creating a copy without using slice?

Hello!

So, what I'm asking is this:

#using slice
favorite_things = ["some list"]
copy_favorite_things = favorite_things[:]

# no slice
favorite_things = ["some list"]
copy_favorite_things = favorite_things

both created a copy, but are there any differences in how python interpret them? Afaik the for loop treated both copies the same way.

Here

#Without slice
   a = [1,2,3]
   b = a
   b.insert(0,0)
Output:
   b = [0,1,2,3]
   a = [0,1,2,3]
#With slice
   a = [1,2,3]
   b = a[:]
   b.insert(0,0)
Output:
   b = [0,1,2,3]
   a = [1,2,3]

1 Answer

Pei Sheng Tan
seal-mask
.a{fill-rule:evenodd;}techdegree
Pei Sheng Tan
Python Web Development Techdegree Student 2,600 Points

Oh wait, this question was addressed in another question I asked. Well, silly me.

So, I'm just going to paraphrase the answer here:

If you didn't use the slice, you didn't really create a copy. You just created another variable that reference the same list you're changing.

I got this answer here: https://teamtreehouse.com/community/for-loop-to-check-element-class-in-list-did-not-work-as-expected