Introduction

List data structure in Python is a compound data types often referred to as sequences. Lists need not be homogeneous. A single list may contain data types like Integers, Strings, as well as Objects. Lists are mutable, and hence, they can be altered even after their creation. List in Python are ordered and have a definite count. The elements in a list are indexed according to a definite sequence and the indexing of a list is done with 0 being the first index. Each element in the list has its definite place in the list, which allows duplicating of elements in the list, with each element having its own distinct index.

Create list

A list is created by placing all the items (elements) inside a square bracket [ ], separated by commas.

# Empty list
my_list = []

# List of integers
my_list = [1, 2, 3]

# List with mixed datatypes
my_list = [1, "Hello", 3.4]

# Having duplicate values
my_list = [1, 2, 4, 4, 3, 3, 3, 6, 5]

Access elements

We can use the index operator [] to access an item in a list. Index starts from 0. Trying to access an element other that this will raise an IndexError. Python allows negative indexing for its sequences. The index of -1 refers to the last item, -2 to the second last item and so on. We can access a range of items in a list by using the slicing operator (colon).

my_list = ['p','r','o','b','e']

# Output: p
print(my_list[0])

# Nested List
n_list = ["Happy", [2,0,1,5]]

# Nested indexing
# Output: a
print(n_list[0][1])

# Last element of the list
# Output: e
print(my_list[-1])

# Output: ['o', 'b', 'e']
print(my_list[2:5])

# Output: ['p']
print(my_list[:-4])

# Output: ['e']
print(my_list[4:])

# Elements beginning to end
print(my_list[:])

Adding element

List are mutable, meaning, their elements can be changed unlike string or tuple. We can use assignment operator (=) to change an item or a range of items. We can add one item to a list using append() method or add several items using extend() method. Use + operator to combine two lists. The * operator repeats a list for the given number of times. Furthermore, we can insert one item at a desired location by using the method insert() or insert multiple items by squeezing it into an empty slice of a list.

my_list = [2, 4, 6]

# Change the 1st item    
my_list[0] = 1            

# Change 2nd to 3th items
my_list[1:3] = [3, 5]  

# Adding single element
my_list.append(7)

# Adding multiple element
my_list.extend([9, 11, 13])

# Output: [1, 3, 5, 7, 9, 11, 13, 9, 7, 5]
print(my_list + [9, 7, 5])

# Output: ['M', 'M', 'M']
print(["M"] * 3)

# Adding element at index 1
my_list.insert(1,3)

# Adding by sequezing
my_list[2:2] = [5, 7]

Removing elements

We can delete one or more items from a list using the keyword del. We can use remove() method to remove the given item or pop() method to remove an item at the given index. The pop() method removes and returns the last item if index is not provided. we can also delete items in a list by assigning an empty list to a slice of elements.

my_list = ['p','r','o','b','l','e','m']

# Delete one item
del my_list[2]

# Delete multiple items
del my_list[1:5]  

# Remove 'p'
my_list.remove('p')

# Remove at index 1
my_list.pop(1)

# Remove last element
my_list.pop()

# Delete using empty list
my_list[2:3] = []

# Clear the list
my_list.clear()
    
# Delete entire list
del my_list

Important Methods

  • append(x) – Add an item to the end of the list.
  • extend(iterable) – Extend the list by appending all the items from the iterable.
  • insert(i, x) – Insert an item at a given position. The first argument is the index of the element before which to insert, so a.insert(0, x) inserts at the front of the list, and a.insert(len(a), x) is equivalent to a.append(x).
  • remove(x) – Remove the first item from the list whose value is equal to x.
  • pop([i]) – Remove the item at the given position in the list, and return it. If no index is specified, a.pop() removes and returns the last item in the list. (square brackets around the i in the method signature denote that the parameter is optional)
  • clear() – Removes all items from the list
  • index(x[, start[, end]]) – Return zero-based index in the list of the first item whose value is equal to x. The optional arguments start and end are interpreted as in the slice notation and are used to limit the search to a particular subsequence of the list. The returned index is computed relative to the beginning of the full sequence rather than the start argument.
  • count(x) – Return the number of times x appears in the list.
  • sort() – Sort items in a list in ascending order
  • reverse() – Reverse the elements of the list in place.
  • copy() – Return a shallow copy of the list. Equivalent to a[:]

References

Data Structures