Mark As Completed Discussion

Array Operations in Python

In the previous lesson, we discussed that string operations are defined by string methods. Similar is the case for Python lists (or arrays). Their operations are also defined using list methods.

The most basic operation of lists is to add new elements to the list. The list name follows a .append() with the element to be added in the parenthesis. The new element is always inserted at the end of the list. An example code is given below.

PYTHON
1fruits = ["apple", "orange", "grapes"]
2fruits.append("strawberry")
3print(fruits) # prints ["apple", "orange", "grapes", "strawberry"]
Array Operations in Python

Another basic operation is the removal of elements from a list. For this, two kinds of methods exist in Python. .pop() removes elements by index number, and .remove() removes by element value. The index number or the element value is specified in the parenthesis. In .pop(), if the index number is not provided, then it removes the last element in the list by default. An example usage is,

PYTHON
1fruits = ["apple", "orange", "grapes", "strawberry"]
2fruits.pop(1)
3print(fruits) # prints ["apple", "grapes", "strawberry"]
4
5fruits.remove("grapes")
6print(fruits) # prints ["apple", "strawberry"]
Array Operations in Python

Another important operation of lists is accessing their length. More than often, we require lists to traverse through all elements in the list (which we will show later in the loops tutorial!). In Python, the len() method is used where the variable name for the list is specified in the parenthesis. For example,

PYTHON
1fruits = ["apple", "orange", "grapes"]
2length = len(fruits)
3
4print(length) # prints 3

A summary of the list methods discussed for Python is listed in the table below.

MethodUsage
append()Insert new element at the end of list
pop()Removing an element from the array using index
remove()Removing an element from the list using element value
len()Length of the list

A comprehensive list of all Python list methods is available here.