# [Tutor] Re: literal number (was: dictionaries)

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Tue, 26 Feb 2002 20:11:33 -0800 (PST)

```On Wed, 27 Feb 2002, Christian Ebert wrote:

> Danny Yoo on Thursday, February 21, 2002 21:34:36 :
>
> > Yes, the sort() method of lists does it in-place, so the code above
> > wouldn't work.  However, we can fix that.  Here's a function that'll
> > return a new sorted list:
> >
> > ###
> > def fsort(L, f=cmp):
> >     """A "functional" sort that returns a copy of L, with all its contents
> >        sorted out."""
> >     L2 = L[:]
>             ^^^
> is this just a stylistic convention or does it make a
> "functional" difference to L2 = L ?

Ah!  This array slice isn't a matter of style --- it's a necessary part of
fsort() because the comment implies that we want to avoid "destructively"
touching the original list.  For example:

###
>>> letters = list('alphacentauri')
>>> letters
['a', 'l', 'p', 'h', 'a', 'c', 'e', 'n', 't', 'a', 'u', 'r', 'i']
>>> another_letters = letters
>>> another_letters.sort()
>>> another_letters
['a', 'a', 'a', 'c', 'e', 'h', 'i', 'l', 'n', 'p', 'r', 't', 'u']
>>> letters
['a', 'a', 'a', 'c', 'e', 'h', 'i', 'l', 'n', 'p', 'r', 't', 'u']
###

When we're modifying lists, we need to be aware of this issue, that
multiple names can refer to the "same" list.

This "mutability" is something that isn't an issue with numbers, because
we can't modify numbers:

###
>>> x = 42
>>> y = x
>>> x = 43
>>> x, y
(43, 42)
###

That is, numbers are "immutable" --- we simply can't change the value of
Pi (as long as we're not in Indiana).

Lists are different because they do have state, and can "mutate" beneath
our fingers.

###
>>> x = ['4', '2']
>>> y = x
>>> x[0] = '2'
>>> x
['2', '2']
>>> y
['2', '2']
###

We can call a dead parrot a "stunned parrot" or an "ex-parrot", but no
matter what we call it, we're talking about the same poor bird.

Thankfully, lists are much easier to clone than birds.

It probably will help readability if we do the copying more explicitly
with the 'copy' module:

###
from copy import copy

def fsort(L, f=cmp):
L2 = copy(L)
...
###

Please feel free to ask questions on this topic; it's a fairly subtle one.
Hope this helps!

```