Looping over lists
Previously, you've used a for
loop to iterate over a list, but you can also use a list comprehension. List comprehensions take the form of [action for item in list]
and return a new list.
We can use the sorted()
function to sort the data in a list from lowest to highest in the case of numbers and alphabetical order if the list contains strings. The sorted()
function returns a new list and does not affect the list you passed into the function. You can learn more about sorted()
in the Python documentation.
A list of lists, records
has been pre-loaded, and each entry is a list of this form:
['2014','F','20799','Emma']
This exercise is part of the course
Data Types in Python
Exercise instructions
- Use a list comprehension on records to create a list called
baby_names
that contains the name, found in the fourth element ofrow
. - Print
baby_names
in alphabetical order using thesorted()
function.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Create the list comprehension: baby_names
baby_names = [____[____] for ____ ____ records]
# Print the sorted baby names in ascending alphabetical order
print(____(____))