Organizing a List
Python provides a number of different ways to organize your lists, depending on the situation.
Sorting a List Permanently with the sort() Method
change the order of the list to store them alphabetically
cars = ['bmw','audi','toyota','subaru']
cars.sort()
print(cars)
['audi', 'bmw', 'subaru', 'toyota']
The sort() method changes the order of the list permanently
You can also sort this list in reverse-alphabetical order by passing the
argument reverse=True to the sort() method
cars = ['bmw','audi','toyota','subaru']
cars.sort(reverse= True)
print(cars)
['toyota', 'subaru', 'bmw', 'audi']
To maintain the original order of a list but present it in a sorted order, you
can use the sorted() function
cars = ['bmw','audi','toyota','subaru']
print("Here is the original list:")
print(cars)
print("\nHere is the sorted list:")
print(sorted(cars))
print("\nHere is the original list again:")
print(cars)
Here is the original list:
['bmw', 'audi', 'toyota', 'subaru']
Here is the sorted list:
['audi', 'bmw', 'subaru', 'toyota']
Here is the original list again:
['bmw', 'audi', 'toyota', 'subaru']
To reverse the original order of a list, you can use the reverse() method
cars = ['bmw','audi','toyota','subaru']
print(cars)
cars.reverse()
print(cars)
it simply reverses the order of the list.
['bmw', 'audi', 'toyota', 'subaru']
['subaru', 'toyota', 'audi', 'bmw']
Finding the Length of a List
You can quickly find the length of a list by using the len() function
cars = ['bmw','audi','toyota','subaru']
print(len(cars))
4