1.4. Basics of List

A list is a collection of items with its own order. The list can contains alphabet, 0-9, strings, etc. In Python, square brackets ([]) indicate a list, and each element in the list are separated by commas.

The print() will return all of the list, including the []. We will see how to get individual items from a list.

Elements in a List

To get an element in a list, we need the index of the item we want. For the first element of the list, write [0] at the end of the list name.

The string method in previous section, such as upper() and lower() can also be used here.

Index 0 is the 1st, 1 is the 2nd

Python sees the first item in a list as a position 0, not position 1. The second item has an index of 1 and so on. For example, to get the fourth item, you need index.

To get the last element in the list, we can use the index -1 like the following example.

Index -2 gives the 2nd item from the end of that list, index -3 will give the 3rd from the end, and so on.

Using Values from a List

Each values from a list can be used like any other variable. Here we will use f-string to create a message based on a value in a list.

Tuple

A tuple looks just like a list except you use parentheses (...) instead of square brackets [...]. The difference with list is that you cannot change the order of element in tuples. Sometimes this is necessary when you specified dimension, position, or list of variables.

Tuples behave almost exactly like list. See the following example.


If we try to change an element in a tuple, Python will give an error.

When compared with lists, tuples are simple data structure. Use them when you want to store a set of values that should not be changed throughout the whole program.

Exercise 1.4

1. List of Colors
Make a list consisting of these colors: red, pink, yellow, and white. Print each color's name by accessing each element in the list, one at a time.

2. Color of the Roses
Using the list in no. 1, print each color name in the following sentence: "I bought a [color name] rose." The output should be four lines of those sentences.

3. The Last Numbers
In the list num_list, write the last and the fifth last number and print it in the following sentence:

The last number is [last number] and the fifth last number is [fifth last number].

4. Adding two coordinates
Let say you have a coordinate called coord_1 which is (5, 6, 2) and another coordinate called coord_2 which is (-2, 3, -4). Try to add the element of index 0 of those two coordinates and save them in a variable called coord_3_x. Then, print it.