Python: List [with methods]

python programs

Summary: In this tutorial, we will learn about the Python list data structure. We will learn to create and use a list in Python, we will perform various operations on it, and most importantly, we will also look at different methods which we can use on the list object in Python.

Introduction to Python List

A list is a data structure in Python that can store a sequence of values of any data type. It is like an array of other programming languages.

In Python, we can construct a list using the square brackets ([]). Every element in a list is separated by a comma (,).

For example, the following list stores three natural numbers:

l = [1, 2, 3]

The list data structure in Python is:

  • Mutable – Means, we can change or update the values stored in a list.
  • Ordered – Items in the list are stored in the order in which they are inserted.
  • Indexed– The list data structure stores each value by associating it with an index. The index number of the first element starts at 0, and it increases gradually with the sequence of items.

For example, in the following list, the index of Python is 0, C++ is 1 and Java is 2:

>>> l = ['Python', 'C++', 'Java']
>>> print(l[0))
Python
>>> print(l[1])
C++
>>> print(l[2])
Java

How can we create a List in Python?

There are two ways to create a list in Python:

  1. Using square brackets ([])
  2. Using list() constructor

Create List using []

Creating a list using [] is very easy. All we need to do is to provide items separated by commas inside the [].

#assign a list to a variable named my_list
my_list=[1, 2, 3]

#list can also hold objects of different data types
my_list=['string', 26, 18.98, 't']

Create List using list()

Alternatively, we can use the inbuilt list() constructor to construct a list in Python.

The constructor can also transform the given values of other data types (such as a string) into a list object.

>>> l = list("code")
>>> print(l)
['c', 'o', 'd', 'e']

Python List Operations

There are various operations such as indexing, slicing, adding and removing items, etc., that we can perform on a Python list. Let’s see some major operations one by one.

Length of List

The len() function, when used on a list, returns the number of items present in it. We can use it to find the size of the given list.

>>> my_list=[1,2,3]
>>> print(len(my_list)) 
3

Access List items

Since the list data structure in Python supports indexing, we can easily access its items using the indexing operator (i.e. []).

>>> my_list = [1, 2, 3, 4]
>>> print(my_list[0])  
1
>>> print(my_list[1])  
2

Note that the indexing in a list starts from 0.

Negative List Indexing

We can take advantage of the negative indexing to access the values of the list from the back.

For example, l[-1] refers to the last item in the list, l[-2] refers to the second-last item in the list, and so on.

>>> my_list = [1, 2, 3, 4]
>>> print(my_list[-1])
4
>>> print(my_list[-2])
3

Slicing of List

Slicing a list means getting a subset of the list based on the index values. In Python, we can easily do so by using a colon (:) inside the indexing operator ([]).

For example, if we want to grab all items in the list after the index ‘x’, we should use the indexing operator as [x:] and for vice versa [:x].

>>> l = [1, 2, 3, 4]
>>> print(l[1:])  
[2, 3, 4]
>>> print(l[:2])
[1, 2]

Note: The [x:] includes the item at index x, whereas the [:x] do not.

If we want to grab items between any two indexes, say x and y, we should use the [x:y] operator on the list.

>>> l = ['A', 'B', 'C', 'D', 'E']
>>> print(l[1:3])
['B', 'C']

Add an Item to List

By using the append() method, we can easily add new items to an existing list.

>>> l = [1, 2, 3, 4]
>>> l.append(5)
>>> print(l)
[1, 2, 3, 4, 5]

Alternatively, we can use the + operator to append items to an existing list. The items which we are adding should also be a list object when using +.

>>> l = [1, 2, 3, 4]
>>> l = l + [5]
>>> print(l) 
[1, 2, 3, 4, 5]

Change an Item in List

To replace any item in the list, use [] operator and assign a new value at its corresponding index.

>>> l = [1, 2, 3, 4]
>>> l[2] = 9
>>> print(l)
[1, 2, 9, 4]

Delete Items from List

In Python, we can remove items from a list either by index or by value, let’s see an example of both.

Remove item by Index

The del() and pop() are the two inbuilt methods using which we can delete any item from the list by its index. All we need to do is to pass the index value as a parameter to these functions.

>>> l = [1, 2, 3, 4]
>>> x = my_list.pop(2)
>>> print(l)
[1, 2, 4]

The only difference between both these methods is that if we do not provide any index value to the pop(), it by default removes the last value of the list and returns the same whereas del() requires the index value and it does not return the value after deletion.

Remove Item by Value

The remove() method of list object removes the first occurrence of the item from the list. This is useful in the situation when we do not know the index value of the item that we want to delete.

>>> l = ['lol', 'ok', 'btw', 'lol']
>>> l.remove('lol')
>>> print(l)
['ok', 'btw', 'lol']

Empty the List

We can use the clear() method on the list object to completely empty the list.

>>> l = ['lol', 'ok', 'btw', 'lol']
>>> l.clear()
>>> print(l)
[]

The clear() method does not accept any parameters.

Check if item exists in a List

To check if an item exists in a list use in and not in operator with the python if statement as follows:

>>> l = ['lol', 'ok', 'btw', 'lol']
>>> if 'btw' in my_list:
...     print("present")
>>> else:
...     print("not present in the list")
present

Iterate through a List

As the list data structure stores multiple items, we may need to iterate through its items to process the data.

In Python, we can easily do so using the for loop as follows:

>>> my_list = ['lol', 'ok', 'btw', 'lol']
>>> for item in my_list:
...     print(item)
lol                                                                                                  
ok                                                                                                   
btw                                                                                                  
lol

In this approach of iteration, we can only access the list items, their indexes remain unknown.

If we also need to know the index of each list item, we should iterate through the range(<length_of_the_list>) as follows:

>>> l = [1, 2, 3, 4]
>>> for i in range(len(l)):
...     l[i] = l[i]*l[i]
>>> print(l)
[1, 4, 9, 16]

Python List Methods

  • sort() – Sort the elements of the list in ascending order.
  • count(x) – Count the frequency of ‘x’ in the list.
  • append(x) – Add ‘x’ to the list.
  • pop() – Remove last element from the list.
  • reverse() – Reverses the list.
  • index(x) – Returns the index of element ‘x’.
  • remove(x) – Removes first appearance of ‘x’ from the list.
  • clear() – Removes all elements from the list.

Quick Revision

#create a list 
my_list=[1,2,3,4]
print(my_list)

#access individual item from a list let say the first item
print(my_list[0])

#grab other items except for the first item
print(my_list[1:])

#adding new item in a list
my_list+['new item']
print(my_list)

#permanently add new item in a list
my_list=my_list=['permanent add']
print(my_list)

#double your list
print(my_list*2)

#append element in a list
my_list.append(5)
print(my_list)

# pop (delete) element from a list
my_list.pop(0)
print(my_list)

Conclusion

A list is a linear data structure in Python that is mutable, ordered, and indexed. It can store multiple data of different data types and is dynamic in terms of size.

We can construct a list either by using square brackets (i.e., []) or by using the inbuilt list constructor in Python.

Leave a Reply

Your email address will not be published. Required fields are marked *