Tuesday, June 11, 2013

A Quick Tip - Sorting Copies

     When you sort a list, the original is lost. If you want to keep the original and sort a copy, you have to do this:

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

numbers2.sort()

print(numbers)

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

print(numbers2)

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

     If you want to know why you need the "[:]," keep reading. If you are not interested, you can skip the next paragraph.

     "numbers2=numbers" means that "numbers2" is "numbers." But, as you learned when you first started lists, "[:]" means all the items in a list, so "numbers2=numbers[:]" makes "numbers2" a list of all the items in "numbers."



     Alright, that was kind of complicated, right? Well there's another way to sort lists--sorted().
      Let's make a new variable:

numbers3=sorted(numbers)

     Now, what did we do?

print(numbers)

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

print(numbers3)

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

     So that's what sorted() does. It gives you a sorted copy of the list, like before.

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.