Lesson 1 ❮ Lesson List ❮ Top Page
❯ 1.4 Lists
⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺
EXPECTED COMPLETION TIME
❲▹❳ Video 7m 41s
☷ Interactive readings 5m
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.
To get an element in a list, we need the index of the item we want. For the 1st element of the list, write [0] at the end of the list name.
1st element = index 0,
2nd element = index 1,
3rd element = index 2 , and so on.
Just like variables, methods can also be used here.
To get the last element in the list, we can use the index -1.
Last element = index -1,
2nd-to-last element = index -2,
3rd-to-last element = index -3, and so on
The method for changing an element in a list is the same as the method for getting an element in a list.
We can simply use = and the desired index as the following example.
It is recommended to split the long list into few lines for readability. One line can have 3-5 items.
Don't forget to add 1 space after each comma as well.
Since Python counts the element from index 0, it can be confusing at first to get the element that we want.
One common error is when we give index that is larger than the size of the list.
One way to resolve this error is to change list_length into list_length - 1.