Python - Sort Lists
Sort List Alphanumerically
• List objects have a sort() method that will sort the list
alphanumerically, ascending, by default:
• Sort the list alphabetically:
Sort List Alphanumerically
• Sort the list numerically:
Sort Descending
• To sort descending, use the keyword argument reverse = True:
• Sort the list descending:
Sort Descending
• Sort the list descending:
Customize Sort Function
• You can also customize your own function by using the keyword
argument key = function.
• The function will return a number that will be used to sort the list (the
lowest number first):
• Sort the list based on how close the number is to 50:
Case Insensitive Sort
• By default the sort() method is case sensitive, resulting in all capital
letters being sorted before lower case letters:
• Case sensitive sorting can give an unexpected result:
Case Insensitive Sort
• Luckily we can use built-in functions as key functions when sorting a
list.
• So if you want a case-insensitive sort function, use str.lower as a key
function:
• Perform a case-insensitive sort of the list:
Reverse Order
• What if you want to reverse the order of a list, regardless of the
alphabet?
• The reverse() method reverses the current sorting order of the
elements.
• Reverse the order of the list items:
Python - Copy Lists
• Copy a List
• You cannot copy a list simply by typing list2 = list1, because: list2 will
only be a reference to list1, and changes made in list1 will
automatically also be made in list2.
• There are ways to make a copy, one way is to use the built-in List
method copy().
• Make a copy of a list with the copy() method:
Python - Copy Lists
• Another way to make a copy is to use the built-in method list().
• Make a copy of a list with the list() method:
Python - Join Lists
• Join Two Lists
• There are several ways to join, or concatenate, two or more lists in
Python.
• One of the easiest ways are by using the + operator.
• Join two list:
Python - Join Lists
• Another way to join two lists is by appending all the items from list2
into list1, one by one:
• Append list2 into list1:
Python - Join Lists
• Or you can use the extend() method, which purpose is to add
elements from one list to another list:
• Use the extend() method to add list2 at the end of list1:
List Methods