Sunday, June 2, 2013

Looping and Sorting Lists

     There's still more about lists, and here's one of the next tricks in the book: looping.
     When you loop through a list, IDLE displays every item in the list on separate lines, and here's how to make that happen:

for i in numbers:
    print(i)

1
2
3
4
5
6

     So that happens. Just for fun, what happens when you do:

for i in numbers:
    print(numbers.index)

<built-in method index of list object at 0x02DA5AD0>
<built-in method index of list object at 0x02DA5AD0>
<built-in method index of list object at 0x02DA5AD0>
<built-in method index of list object at 0x02DA5AD0>
<built-in method index of list object at 0x02DA5AD0>
<built-in method index of list object at 0x02DA5AD0>

     I just wanted to show you that. Now, let's move on to sorting, as you know from the title.
     Let's mix up the items in our list:

numbers=['4', '1', '6', '2', '5', '3']

     sort() rearranges the list alphabetically and/or numerically. Let's try it with this list.

numbers.sort()

print(numbers)

['1', '2', '3', '4', '5', '6']

     Magic! No, not really.
     Now, what if we wanted to sort in reverse order? We use reverse().

numbers.reverse()

print(numbers)

['6', '5', '4', '3', '2', '1']

     More magic! No, it's not magic. It's technology. There's another way we can reverse lists:

numbers.sort(reverse=True)

print(numbers)

['1', '2', '3', '4', '5', '6']

     People would probably prefer reverse() because it's a little faster to type and easier to remember, but you can choose what you want.

1 comment: