BaşlayınÜcretsiz Başlayın

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']

Bu egzersiz

Data Types in Python

kursunun bir parçasıdır
Kursu Görüntüle

Egzersiz talimatları

  • Use a list comprehension on records to create a list called baby_names that contains the name, found in the fourth element of row.
  • Print baby_names in alphabetical order using the sorted() function.

Uygulamalı interaktif egzersiz

Bu örnek kodu tamamlayarak bu egzersizi bitirin.

# Create the list comprehension: baby_names
baby_names = [____[____] for ____ ____ records]
    
# Print the sorted baby names in ascending alphabetical order
print(____(____))
Kodu Düzenle ve Çalıştır