Chapter 3: (Continued)
cars = [‘bmw’, ‘audi’, ‘toyota’, ‘subaru’]
print(“Here is the original list:”)
print(cars)
print(“\nHere is the sorted list:”)
print(sorted(cars))
print(“Here 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’]
- Sorting a list alphabetically is more complicated when all of the values are not in lowercase
Printing a list in reverse order
- reverse() method – used to reverse the original order of a list
- if the list of cars is in chronological order according to when we owned them, we can reverse it
cars = [‘bmw’, ‘audi’, ‘toyota’, ‘subaru’]
print(cars)
cars.reverse()
print(cars)
[‘bmw’, ‘audi’, ‘toyota’, ‘subaru’]
[‘subaru’, ‘toyota’, ‘audi’, ‘bmw’]
- reverse() method changes order permanently but can be used again to revert to the original order
Finding the length of a list
len() function – find the length of a list
>>> cars = [‘bmw’, ‘audi’, ‘toyota’, ‘subaru’]
>>> len(cars)
4
- helpful when determining amount of data or registered users on a site
Avoiding index errors when working with lists
- index error – Python can’t find an item a the index you requested
motorcycles.py
motorcycles – [‘honda’, ‘yamaha’, ‘suzuki’]
print(motorcycles[3])
IndexError: list index out of range
- can use index -1 unless the list is empty
Summary
- learned about lists and how to work with individual items in a list
- learned how to define a list and how to add and remove elements
- learned how to sort lists permanently and temporarily
- learned how to find the length of a list and how to avoid index errors