# Newbie question - sorting a slice

Discussion in 'Python' started by hwg, Aug 29, 2007.

1. ### hwgGuest

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

hwg, Aug 29, 2007

2. ### Guest

On Aug 28, 7:43 pm, hwg <> 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

sort() works on a list in place, and returns none

You have to make a temp list.

note...
>>> letters = ['d', 'a', 'e', 'c', 'b']
>>> print letters.sort()

None
>>> print letters

['a', 'b', 'c', 'd', 'e']

~Sean

, Aug 29, 2007

3. ### Paul McGuireGuest

On Aug 28, 9:43 pm, hwg <> 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
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'].

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

Paul McGuire, Aug 29, 2007