Gotta' Sort'em All!
Sorting: Any process of arranging items systematically.
We can sort a list temporarily by using the
sorted() function. The
sorted function lets you temporarily sort the list but
it doesn't affect the original list.
cars = ['bmw', 'audi', 'toyota', 'subaru']
# Temporarily sort the cars in alphabetical order
print(sorted(cars))
# The original list is left untouched.
print(cars)
> ['audi', 'bmw', 'subaru', 'toyota']
> ['bmw', 'audi', 'toyota', 'subaru']
We can provide the argument
reverse = True to the
sorted() function to
print the sorted list in reverse order Temporarily.
cars = ['bmw', 'audi', 'toyota', 'subaru']
# Temporarily sort the cars in alphabetical order
print(sorted(cars, reverse=True))
# The original list is left untouched.
print(cars)
> ['toyota', 'subaru', 'bmw', 'audi']
> ['bmw', 'audi', 'toyota', 'subaru']
We can permanently reverse the order of a list.
cars = ['bmw', 'audi', 'toyota', 'subaru']
cars.reverse()
# The original list is permanently reversed
print(cars)
> ['subaru', 'toyota', 'audi', 'bmw']
Python allows us to quickly sort a list in alphabetical order with
the sort() method
cars = ['bmw', 'audi', 'toyota', 'subaru']
# Sort the cars permanently in alphabetical order
cars.sort()
print(cars)
> ['audi', 'bmw', 'subaru', 'toyota']
You can sort a list in reverse order by passing the argument of
reverse=True into
the sort method.
cars = ['bmw', 'audi', 'toyota', 'subaru']
# Sort the cars in reverse alphabetical order
cars.sort(reverse=True)
print(cars)
> ['toyota', 'subaru', 'bmw', 'audi']
We can find how long a list is by calling the
len() function on a
list.
cars = ['bmw', 'audi', 'toyota', 'subaru']
# Print the length of the list.
print(len(cars))
> 4