Python | Data Types | Lists

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
square brackets [ ]. 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 print() function.

print(fruits)

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[1]

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.

print(unknown_fruit)

Let’s say that you want to replace an item in the list. For example, let’s replace “bananas” with “pears”.

fruits[1] = “pears”

Now, if we print the “fruits” list we get ['apples', 'pears', 'mangoes'].

Manipulating Lists

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: insert,append, and remove.

You can insert an item in the list as it is shown below.

fruits.insert(0,’watermelon’)

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.

fruits.append(‘plums’)

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.

fruits.remove(‘bananas’)

This removes the item “bananas” from the list.

Leave a Reply