Lists are collections of interrelated values. Lists can be manipulated and they can contain any data types.
Defining a list starts with the variable name followed by the assignment operator then followed by
[ ]. Inside the square brackets you can place the items of the list separated by comma.
fruits = [‘apples’,’bananas’,’mangoes’]
You can print the list easily by using the
Each item of the list has an index number. The first item of any list has the index zero (
0), the second number has the index one (
1), the third item has the index two (
2), and so on.
If you want to access an item of the list you can use a code as is shown below:
unknown_fruit = fruits
That means I want to access the element with the index 1 (which is the second element in the list) of the list “fruits”. Since I don’t know the element I named it
unknown_fruit. Now, let’s print it on the screen.
Let’s say that you want to replace an item in the list. For example, let’s replace “bananas” with “pears”.
fruits = “pears”
Now, if we print the “fruits” list we get
['apples', 'pears', 'mangoes'].
We are going to take a look at three very important functions that allow you to manipulate the items in a list. These three functions are:
You can insert an item in the list as it is shown below.
This will insert “watermelon” as the first item of the list (index 0).
You can append an item in the list as it is shown below.
This will insert the item “plums” at the end of the list (the last element).
You can remove an item in the list as it is shown below.
This removes the item “bananas” from the list.