Back-To-School Deals - hours only!Up to 80% off on all courses and bundles.-Close
Recap
2. Python lists
Iterating over a list
Modifying lists
Working with multiple lists
Congratulations

Instruction

Great! Before we move on to list usage in Python, let's do a quick recap of the basics. Lists are data structures typically used to store elements of the same type. List elements are ordered – i.e., each element is assigned a unique integer index.

list

The code below shows the ABCs of list handling:

  1. Define a list:
  2. countries = ['Spain', 'France', 'USA']
  3. Access the first element:
  4. countries[0]
  5. Access the second and third elements:
  6. countries[1:3]
  7. Add a new element:
  8. countries.append('Mexico')
  9. Delete by index:
  10. del countries[2]
  11. Delete by value:
  12. countries.remove('Spain')
  13. Iterate over the list:
  14. for country in countries:
      print(country)
  15. Check if the list contains an element:
  16. if 'Germany' in countries:
      print('Ich spreche Deutsch!')

Exercise

Let's do a quick list exercise as a warm-up. You are given a list of countries. Do the following:

  • Remove the UAE from the list.
  • Add Japan to the list.
  • For each country in the modified list, print the following sentence:
    {country} contains {len(country)} letters!

Stuck? Here's a hint!

Use the following for loop:

for country in countries:
  print(country, 'contains', len(country), 'letters!')