Lists – How Python Works with a Collection of Values

The lists in Python is one of the reasons why I fell in love with Python. They make many things easy and elegant to work with in Python.

The best way to think of a Python list, is just to think of it as a list of items.

  • Step 1: See the code below and execute it.
  • Step 2: Inspecting that code carefully, how would you print the last element of the list (the 5th element)?
  • Lesson:
    • You create a list with square brackets (example l = [0, 2, 2, 1])
    • You can print the entire list by print the variable assigned to it (example, print(l))
    • You print the ith element by print(l[i-1], because we index from 0 (i.e., the first element is indexed by 0).
  • Step 3: As the example below shows, a list can contain any of the primitive types (integers, floats and strings).
  • Lesson:
    • A list can contain elements (also others than the primitive types you know so far)
    • You can access the elements in the list by using index (e.g. my_list[0] + my_list[1])
  • Step 4: Investigate the code below and guess what it will print.
  • Lesson: You can change the values in the list by assigning new ones (example my_list[3] = 16)
  • Step 5: Try to change the list to print [4, 3, 2, 1, 0] by assigning each entry to the value.
  • Step 6: Try to assign a value to an index out of range and see what happens (example my_list[19] = 12)
  • Lesson: You cannot access or assign an index out of range in a list, i.e. if a list has 10 elements, you cannot access or assign values greater than that.
  • Step 7: See the code below and guess what it will print.
  • Lesson: You can add new elements to the end of the list by calling append (example my_list.append(4)).
  • Step 8: Try to change the last element added to the list to 9.
  • Step 9: Wow? That looks strange. Will that work? See the code below and try it out.
  • Lesson: You can concatenate lists by “adding” them together.
  • Exercise:
    • Insert the missing code, such that it will work.
    • Hint 0: Use append to my_list
    • Hint 1: See an example of a solution by pressing the solution.py tab below.

Leave a Reply