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.

No comments:

Post a Comment