Storing dynamic amounts of data
At this point in the course, you have learned how to create types that store a set number of values. For instance, the previously introduced Tuple type always stores two values. It is possible to add further fields to the type, but that does not change the fact that the amount is fixed.
To store dynamic amounts of data, we can make use of a type called List from the standard library. Being able to store a dynamic amount of data means that we can add or remove an element at any time, even when the program is already running. A list can only store elements of the same type, which is determined by its only placeholder type. In the following example, a list called users is created with User as its placeholder type, meaning we can only add instances of User into the list. Initially, the list does not contain any items. However, by using the method called append, we can append items to the end of the list. We can confirm this by printing out the contents of the list.
Output:
We can access elements in the list by calling the method called at with an index. An index is a number that represents the position of where an element is stored in the list. An important aspect to mention is that the index 0 represents the first item in the list, not index 1. If you would like to know how many items are stored in the list, you can call the method called size on the list.
Output:
In case you would like to remove an item from the list, you can make use of the remove_at method, which also takes an index of the item to remove as a parameter. To remove the last item in a list, you need to calculate the index of the last element and pass it to remove_at. The index of the last element can be calculated by subtracting 1 from the size of the list (remember: indices start at 0!).
Output:
Calculating prime numbers
The following example combines many important aspects that have been introduced in the previous chapters, such as functions, loops, conditions, placeholders, and lists. In the example, the first n prime numbers are calculated, with n being requested from the user. If you can understand this example, you are well-equipped for moving on to the next chapters. If not, you should consider going back through the previous chapters until you fully understand this example.