Lesson 39 +10 XP

Sort, Copy, and Join Lists

Sort, Copy, and Join Lists

The everyday operations for managing list order and combining lists.

Sort ascending

thislist = ["orange", "mango", "kiwi", "pineapple", "banana"]
thislist.sort()
print(thislist)  # ['banana', 'kiwi', 'mango', 'orange', 'pineapple']

Sort descending

thislist.sort(reverse=True)

Sort numbers

numbers = [100, 50, 65, 82, 23]
numbers.sort()
print(numbers)  # [23, 50, 65, 82, 100]

Reverse order

reverse() flips the current order without sorting:

thislist.reverse()

Copy a list (careful!)

mylist = thislist does NOT copy; both names point to the same list. Use copy():

mylist = thislist.copy()

Or slice it:

mylist = thislist[:]

Join lists

list1 = ["a", "b"]
list2 = [1, 2, 3]
list3 = list1 + list2
print(list3)  # ['a', 'b', 1, 2, 3]

Or use extend():

list1.extend(list2)
print(list1)  # ['a', 'b', 1, 2, 3]

TL;DR

  • sort() orders; sort(reverse=True) reverses the order.
  • reverse() flips the current order.
  • copy() or [:] makes a real copy.
  • + and extend() join lists.