Velocity Reviews > Newbie question - sorting a slice

# Newbie question - sorting a slice

hwg
Guest
Posts: n/a

 08-29-2007
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

half.italian@gmail.com
Guest
Posts: n/a

 08-29-2007
On Aug 28, 7:43 pm, hwg <(E-Mail Removed)> 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

Paul McGuire
Guest
Posts: n/a

 08-29-2007
On Aug 28, 9:43 pm, hwg <(E-Mail Removed)> 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