title: python list mutation in loops, global modifying vs. local modifying
body: <p>Halp, perhaps someone more experienced than I am with Python can answer this (noobish) question.</p>
  
  <p>I'm having trouble figuring out why the following behavior occurs with lists.</p>
  
  <p>Let's have the following functions:</p>
  
  <pre><code>def foo1(L):
     """
      L is a list
     """
     L = ['new', 'stuff']
     print L
  
  def foo2(L):
     """
      L is a list
     """
     L[:] = ['new', 'stuff']
     print L
  </code></pre>
  
  <p>IDLE outputs the following:  </p>
  
  <pre><code>&gt;&gt;&gt;L = [1,2,3]  
  &gt;&gt;&gt;foo1(L)  
  ['new', 'stuff']  
  &gt;&gt;&gt;L  
  [1,2,3]  
  
  &gt;&gt;&gt;foo2(L)  
  ['new', 'stuff']  
  &gt;&gt;&gt;L  
  ['new', 'stuff']
  </code></pre>
  
  <p>I can't figure out why the first function only temporarily modifies the list, but the second modifies the list globally. I don't think it's a scope issue, but rather an issue with L= versus L[:]=</p>
  
  <p>I know that if I use list comprehension to change L or use something like L.append() or some other method to mutate L within a function, then it modifies L globally, too. </p>
  
  <p>I'm not all the new to Python, but, usually, I just google for solutions to my problems when coding, and, if it works, I don't question it. I'm taking time this summer to actually learn best-practices and get at the meat of python. </p>
  
  <p><strong>Edits:</strong>
  So Martijn decided to mark this question as a duplicate, but I disagree. The linked question does not address my question.  </p>
  
  <p>When a variable is passed to a function, the function creates a new environment with its own scope. The variables in this environment exist only in the scope of that environment, and nowhere else. Hence, when my list L is passed to both foo1 and foo2, a temporary list, L, is made within the scope of only that function call. In other words, prior to calling foo1(L), there exists a list named L which is equal to [1,2,3]. After the call foo1(L), a new function environment is made, and it contains a temporary list, also called L, which lives only in the scope of that function. If I modify L via L = [blah, blah, blah] within the function, nothing happens to the original list L. However, by using [:] on L within the function, the original list is now modified. Why? How does python know after it has created a temporary variable with limited scope, that it needs to modify the original one with global scope? This concept does not make sense to me.</p>