Newbie question - sorting a slice

H

half.italian

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
 
P

Paul McGuire

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,754
Messages
2,569,528
Members
45,000
Latest member
MurrayKeync

Latest Threads

Top