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

trying to understand, for marbles in bundle[:]:

if I try to modify the list with

bundle[:].insert(0, new_marble)

the list doesn't change. If I modify the list with

bundle.insert(rn, new_marble)

both bundle and bundle[:] are modified.

  • here is the code I'm using to try to sort this out
import random

bundle = ["red", "green", "blue"]
print(bundle)
print(bundle[:])
for marbles in bundle[:]:
    if len(bundle) < 6:
        new_marble = input("Add a new marble: ")
#run w/just this both bundle and bundle[:]change
        bundle[:].insert(0, new_marble)
#w/o this, no change to bundle
        bundle.insert(0, new_marble)
        print(bundle)
        print(bundle[:])

1 Answer

bundle[:].insert() creates a copy of your list, but you need to assign it to a new variable. That's why it's not appearing that you are modifying anything. You are, but you aren't saving your changes anywhere.

bundle.insert() changes both because you are changing both and then creating a copy of bundle with bundle[:]. So the copy has the change made to the original.

Try making a copy of bundle with bundle[:] and assigning it to a new name, then modifying either the bundle or the copy, and then printing both out. They should come out different then.