Skip to content

Python Course – 3. Collections

Learn Python collections: lists, sequences, tuples and dictionaries, with videos, theory slides and hands-on exercises from the jarroba Python course.

What is a <Collection> in real life? A collection of trading cards, a collection of stamps, a collection of students, a collection of numbers, and so on. In programming, values can be grouped into <Collections> of several values, depending on how we want to store them.

Theory

Skip to PDF content

3.1- Lists

One value, then we add another, followed by more values; and we store them in a list so we can get each value in order or find it easily. 

Note

To learn more, check out these posts:

3.2- Sequences

A movie is a sequence of frames and a text is a sequence of letters; by the same logic, several elements in order form a sequence of elements.

Note

To learn more, check out these posts:

3.3- String to List – List to String

A text can be split into letters, and several words can be joined into a paragraph.

3.4- Tuples

We can group several values that will never be modified into a tuple. A tuple is ideal for using several values at once.

3.5- Tuples – Function Return

Returning one value from a function is easy; returning many values from a function is just as easy, with tuples.

3.6- Dictionaries

If we have a list of hotels and we want each hotel to store its number of stars, a list won’t do. However, we can do this with a dictionary, whose elements are key-value pairs, where the key is the name of the hotel and the value is the number of stars.

Exercises

Exercise 3.1-texto.py

  1. Create a text of at least 10 characters
  2. Print the letter at index 7
  3. Print the letters in the range from position 3 to 8

Exercise 3.2-supermercado.py

Copy the following list: lista_de_inicio

lista_de_inicio = [
    "fruta y verduras",
    "carnes y pescados",
    "lácteos y huevos",
    "dulces y pan",
    "hogar y jardín",
    "cuidado y limpieza"
]
  1. Print the length of the list
  2. Remove the element “hogar y jardín” (hint: use the position)
  3. Insert the element “entretenimiento y deportes” into the list
  4. Print each of the elements (by position) formatted as: “En el mercado hay {primero} pero no {segundo}”. To get primero and segundo, they are each of the lines split by ” y ” (hint: create a list from a String with split. Example: “fruta y verduras”.split(” y “) ).

Example for the first element: “fruta y verduras” (primero will be “fruta” and segundo “verduras”). It has to print: “En el mercado hay fruta, pero no verduras”.

Exercise 3.3_lista_campeones_del_mundo.py

Given the following variables, which represent the players of the Spanish national football team that played in the 2010 World Cup:

portero = "Casillas"
defensas_titulares = ["Ramos", "Pique", "Puyol", "Capdevila"]
centrocampistas = ["Xabi Alonso", "Busquets", "Xavi Hernandez", "Iniesta"]
delanteros = ["Pedrito", "Villa"]
suplentes = ["Marchena", "Torres", "Valdes", "Fabregas", "Mata", "Arbeloa",
             "Llorente", "Javi Martinez", "Silva", "Reina", "Navas"]

You are asked to:

  1. Count how many forwards Spain played with in the World Cup final. (the delanteros list)
  2. Create a new list called “titulares” containing the starting players of the Spanish team.
  3. In the 60th minute of the match a substitution is made: Navas comes on for Pedrito. In the “titulares” list you have to add
    Navas, who is in the “suplentes” list, and remove Pedrito from the starters list and add him to the substitutes list.
  4. Create a list called “selección” containing all the players of the Spanish team.

Exercise 3.4_lista_campeones_del_mundo_dorsal.py

Given the following list:

futbolistas = ["1 - Casillas", "15 - Ramos", "3 - Pique", "5 - Puyol",
               "11 - Capdevila", "14 - Xabi Alonso", "16 - Busquets",
               "8 - Xavi Hernandez", "18 - Pedrito", "6 - Iniesta",
               "7 - Villa"]

You are asked to sort the list in descending order by the player’s shirt number. The result must be the following:

['18 - Pedrito', '16 - Busquets', '15 - Ramos', '14 - Xabi Alonso', '11 - Capdevila', '8 - Xavi Hernandez', '7 - Villa', '6 - Iniesta', '5 - Puyol', '3 - Pique', '1 - Casillas']

Exercise 3.5_diccionario_campeones_del_mundo.py

Given the following dictionary, which represents the players of the Spanish national football team that played in the 2010 World Cup:

futbolistas = {
    1: "Casillas", 15: "Ramos",
    3: "Pique", 5: "Puyol",
    11: "Capdevila", 14: "Xabi Alonso",
    16: "Busquets", 8: "Xavi Hernandez",
    18: "Pedrito", 6: "Iniesta",
    7: "Villa"
}

You are asked to:

  1. Count the number of players (elements) in the dictionary.
  2. Change the name “Casillas” to “Iker Casillas” in the dictionary.
  3. In the 60th minute of the match a substitution is made: “Navas” comes on with shirt number 22 for “Pedrito” (number 18). In the
    87th minute another substitution is made: “Fabregas” comes on with number 10 for “Xabi Alonso” (number 14). You have to remove the two starting players from the dictionary and add the two new players.
  4. Create a list with the shirt numbers of the players in the dictionary.
  5. Create a list with the names of the players in the dictionary.
  6. Create a copy of the “futbolistas” dictionary called “campeones_del_mundo”.
  7. Delete the “futbolistas” dictionary.

“Python Course – 3. Collections” by Ramón Invarato at jarroba.com, licensed under Creative Commons Attribution-NonCommercial-ShareAlike 3.0. Registered at Safe Creative.

Ramón Invarato

I design and build data platforms and intelligent systems, and I enjoy sharing that experience here.

You may also like

Building Your Own Collection in Python

Learn how to build your own Collection in Python step by step: Container, Sized and Iterable explained, plus the difference between an Iterator and an Iterable.

May 27, 2018

Python Lists, with Examples

Lists in Python are a data structure that stores an ordered collection of items, which don't have to be of the same type. Learn how to use them with examples.

Apr 6, 2015

Comments

Leave a comment


This site uses Akismet to reduce spam. Learn how your comment data is processed.