Python Lists Tutorial

The list datatype is the most general sequence provided by the Python programming language. In this article, I’ll walk you through a tutorial on Python lists.

Python Lists

Lists are collections ordered by the position of arbitrarily typed objects and they have no fixed size. They are also mutable unlike strings, lists can be changed in place by assigning offsets as well as various list method calls. As a result, they provide a very flexible tool for representing arbitrary collections, lists of files in a folder, employees of a company, emails in your inbox, etc.

Since these are sequences, lists support all types of sequence operations, let’s take a look at some sequence operations from Python lists:

L = [123, 'spam', 1.23]
len(L)
3

we can also do indexing and slicing on it:

L[0]
123
L[:-1]
[123, 'spam']

Type Specific Operations

Lists in Python may be reminiscent of arrays in other languages, but they tend to be more powerful. On the one hand, they don’t have a fixed type constraint, the list we just looked at, for example, contains three objects of completely different types. Also, the lists do not have a fixed size. In other words, they can grow and shrink on demand, in response to specific list operations:

L.append('NI')
L
[123, 'spam', 1.23, 'NI', 'NI', 'NI']
L.pop(2)
1.23

Here the append method increases the size of the list and inserts an item at the end; the pop method then removes an item at a given offset, which shrinks the list. Other list methods insert an element at an arbitrary position, remove an element given by value, add multiple elements at the end, etc. Because lists are editable, most list methods also modify the list object in place, instead of creating a new one:

M = ['bb', 'aa', 'cc']
M.sort()
M
['aa', 'bb', 'cc']
M.reverse()
M
['cc', 'bb', 'aa']

The list sort method here, for example, sorts the list ascending by default, and reverses the reverse in either case, the methods modify the list directly.

Nested Lists in Python

One cool feature of Python’s basic data types is that they support arbitrary nesting where we can nest them in any combination, and as deep as we want. For example, we can have a list which contains a dictionary, which contains another list, and so on. 

An immediate application of this functionality is to represent multidimensional matrices or arrays in Python. So let’s see how to create nested lists with Python:

M = [[1, 2, 3],
     [4, 5, 6],
     [7, 8, 9]]
M
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]

I hope you liked this article on a tutorial on Python Lists. Feel free to ask your valuable questions in the comments section below.

Default image
Aman Kharwal
Coder with the ♥️ of a Writer || Data Scientist | Solopreneur | Founder
Articles: 1054

Leave a Reply