Python List Operations

Hanzel Godinez H.
Dev Genius
Published in
5 min readJul 5, 2020

--

Most common operations on lists in Python

List Operations

Before starting with the operations supported by lists in Python, I would like to recommend the article Python data types, this is a good article before starting with slightly more advanced articles.

I would like to remind you that the lists in Python are a very powerful and highly used data type. Lists are very similar to arrays in others programming language, but with steroids, since in Python the lists can contain a combination of data types such as strings, tuples, lists , dictionaries, functions, file objects, and any type of number.

Lists examples:

x = [2, 6, 4.5, "seven", ["a", "b"], (5, 0)]y = []matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

Now, we understand lists better, let’s look at the different operations supported for these in Python.

List operations

I will do a grouping of the list operations according to the impact on these, my goal is making easier the explanation and understanding:

1. Definition operations

These operations allow us to define or create a list.

1.1. [ ]

Creates an empty list.

y = []

2. Mutable operations

These operations allow us to work with lists, but altering or modifying their previous definition.

2.1. append

Adds a single item to the bottom of the list.

x = [1, 2]x.append('h')print(x)Output:[1, 2, 'h']

2.2. extend

Adds another list to the end of a list.

x = [1, 2]x.extend([3, 4])print(x)Output:[1, 2, 3, 4]

2.3. insert

Inserts a new element at a specific position in the list, this method receives the position as a first argument, and the element to add as a second argument .

x = [1, 2]x.insert(0, 'y')print(x)Output:['y', 1, 2]

2.4. del

Deletes the element located in the specific index. This method also has the possibility to remove a section of elements from the list, through the “:” operator. You only need to define a starting and end point [start:end], keep in mind that the end point will not be considered. These points can be ignored, whereby the 0 position will be the starting point, and the last position in the list will be the end point.

x = [1, 2, 3]del x[1]print(x)Output:[1, 3]y = [1, 2, 3, 4, 5]del y[:2]print(y)Output:[3, 4, 5]

2.5. remove

Removes the first match for the specified item.

x = [1, 2, 'h', 3, 'h']x.remove('h')print(x)Output:[1, 2, 3, 'h']

2.6. reverse

Reverses the order of the elements in the list, this places the final elements at the beginning, and the initial elements at the end.

x = [1, 2, 'h', 3, 'h']x.reverse()print(x)Output:['h', 3, 'h', 2, 1]

2.7. sort

By default, this method sorts the elements of the list from smallest to largest, this behavior can be modified using the parameter reverse = True.

x = [3, 2, 1, 4]x.sort()print(x)Output:[1, 2, 3, 4]y = ['R', 'C', 'Python', 'Java', 'R']y.sort(reverse=True)print(y)Output:['R', 'R', 'Python', 'Java', 'C']

It is important to know that when you apply the sort method, you must do it on lists that have elements of the same data type, otherwise, you will face the TypeError exception.

One of the benefits of the sort method is the custom sorting. We just need to create a function that sorting under some custom criteria, and then we can use it through the key argument. Keep in mind that custom sorting is slower than the default sort.

Custom sorting example:

def sorting_by_length(str):
return len(str)

x = ['Python', 'is', 'the', 'best']
x.sort(key=sorting_by_length)print(x)

3. Immutable operations

These operations allow us to work with lists without altering or modifying their previous definition.

3.1. sorted

This method sorts the elements of a list from smallest to largest, this is very similar to the sort method, but this behavior can be modified using the parameter reverse = True.

x = [5, 2, 9, 0]print(sorted(x))print(x)Output:[0, 2, 5, 9][5, 2, 9, 0]

Something interesting about the sort method is that it is not limited to lists, it also works for tuples and dictionaries, this a subject that we will be talking in another article.

3.2. +

This operation allows us to concatenate or join two different lists in a new list.

x = [1, 2, 3]y = [4, 5, 6]print(x + y)print(x)print(y)Output:[1, 2, 3, 4, 5, 6][1, 2, 3][4, 5, 6]

3.3. *

This operation will replicate a list to the specified number of times.

x = [1, 2, 3]print(x * 3)print(x)Output:[1, 2, 3, 1, 2, 3, 1, 2, 3][1, 2, 3]

3.4. min

This method returns the smallest element in a list.

x = [40, 100, 3, 9, 4]print(min(x))print(x)Output:3[40, 100, 3, 9, 4]

3.5. max

Unlike the min method, this returns the largest item in a list.

x = [40, 100, 3, 9, 4]print(max(x))print(x)Output:100[40, 100, 3, 9, 4]

3.6. index

Returns the position in the list of the specified element.

x = [10, 30, 20]print(x.index(30))print(x)Output:1[10, 30, 20]

3.7. count

Returns the number of times the specified item occurs in the list.

x = [10, 30, 20, 30, 30]print(x.count(30))print(x)Output:3[10, 30, 20, 30, 30]

3.8. sum

This method sums the items of the list, just if they can be summed. Sum is a widely used method with numeric type lists.

x = [2.5, 3, 3.5]print(sum(x))print(x)Output:9.0[2.5, 3, 3.5]

3.9. in

Returns only two possible values ​​True when the element is in the list, and False when it is not. This method is widely used to avoid exceptions in methods such as: index and remove. In case that the searched element is not found in the list, it will result in an exception.

x = ['h', 2, 'a', 6, 9]print('a' in x)print(x)Output:True['h', 2, 'a', 6, 9]

These are some of the most common and important operations related to Python lists, from my point of view, it is very helpful to know them in detail, due to you usually will work with these structures and of course with their operations.

I invite you to comment on any detail that has not been mentioned. I am sure that your contribution will be very valuable.

Before saying goodbye, I leave the following link where you can get a cheat sheet with all list operations.

Thank you very much for getting here. 😊 👈

This article is inspired in the book 📖 “The Quick Python Book” 📖, which I recommend you widely, if you want to know the basic concepts of the language, and at the same time, to learn about other advanced topics.

--

--