Information about cookies on this page

Our website uses cookies to ensure the functionality of the website, to collect and analyze information about the performance and usage of the website. Privacy Policy

  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in
  
  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in

Nested Lists

An element of a list can be any value, even another list. A list inside a list is called a nested list. Nested lists are useful for data that comes in groups, such as study groups:

study_groups = [["Jennifer", "Boris"], ["David", "Ava", "Nancy"]]
print(study_groups)

This prints:

[['Jennifer', 'Boris'], ['David', 'Ava', 'Nancy']]

The list study_groups has two elements, and each of them is a list of names: one study group. The first index selects a group, which is an ordinary list:

print(study_groups[1])

This prints:

['David', 'Ava', 'Nancy']

To get one student, add a second index in square brackets. study_groups[1][0] first takes the element at index 1 (the second group, ["David", "Ava", "Nancy"]) and then, from that list, the element at index 0:

print(study_groups[1][0])

This prints:

David

Everything you know about lists works for the inner lists too. len(study_groups) is 2, the number of groups, while len(study_groups[1]) is 3, the number of students in the second group. study_groups[0][-1] is the last student of the first group, "Boris". And study_groups[0].append("Tim") adds Tim to the end of the first group.

Instructions

  1. 1

    Print the first member of the second team. Use two indexes.

  2. 2

    Tim has joined the first team. Add "Tim" to the end of the first team, teams[0], with append().

  3. 3

    Print the whole list teams. The output should be [['Peter', 'Lucy', 'Tim'], ['Daniel', 'Ava']].

Back

10/12

  1. 1. Introduction to Lists
  2. 2. Creating Lists
  3. 3. Accessing List Elements
  4. 4. Changing List Elements
  5. 5. Length and the Last Element
  6. 6. Adding Elements: append()
  7. 7. Removing Elements: pop()
  8. 8. Removing by Value: remove()
  9. 9. Searching a List: in
  10. 10. Nested Lists
  11. 11. Characters of a Text
  12. 12. Summary
Next

Try it yourself

Do this exercise right here in your browser. No account needed.