Newbie question - sorting a slice

Paul McGuire ptmcg at austin.rr.com
Tue Aug 28 23:06:47 EDT 2007


On Aug 28, 9:43 pm, hwg <hwg... at yahoo.com> wrote:
> I've searched the group and didn't see the answer to this...
>
> Why doesn't this work?:
>
> >>> letters = ['d', 'a', 'e', 'c', 'b']
> >>> letters[1:3].sort()
>
> This returns None.
>
> Why?  letters[1:3]  is  ['a', 'e', 'c']    Sorting that should return
> ['a', 'c', 'e']
>
> hwg

There are a couple of flaws in your example.

letters[1:3] is not ['a', 'e', 'c'], but is just ['a','e'].  The
elements of a slice start with the lower-bound INclusive (zero-based,
so this is 'a'), up to the upper bound EXclusive (up to, but NOT
INCLUDING 'c').  The slice returns a copy of the selected elements.

.sort() does an in-place sort, and returns None.  You may instead use
the builtin function sorted(), as in:

sorted(letters[1:4])

which in fact DOES return ['a', 'c', 'e'].

What your example had done was:
1. choose 2 elements of a list and copy them to a temporary list
2. sort the list in place
3. return None
4. discard the temporary list, since all references to it were gone

For remedial study:
- study notation for slices
- study the difference between list.sort() and sorted()

-- Paul




More information about the Python-list mailing list