Python Lists

Table of contents:

Python Lists

Python lists are very powerful and support a very large number of operations. Here, we are going to learn the very basics of a python lists.

This page goes through the basics of python lists and indexing of list items. The list slicing page contains a detailed discussion on list slicing and slice assignment. The list methods page contains a detailed discussion on list methods.

Table of contents:

What are python lists

A python list is an ordered collection of objects contained in a pair of square brackets separated by commas. Or simply, it is a sequence of values. The literal [1, 2, 3] is a valid python list. Let us display it in IDLE shell:

[1, 2, 3] is a list literal. It is of 'list' data-type.

We can assign this list literal [1, 2, 3] to a variable.

Variable a is now of list-type.

Empty lists

A list can hold any number of objects, or no objects at all. We can create an empty list as in the following.

We can also create an empty list by calling the python list() function.

Once an empty list is created, we can add items to it with .append(), because lists are mutable.

Properties of a List

Lists are ordered

Lists are ordered. Each item of a list has a positional value or index. In a list [55, -6, 3.4], 55 has position 0, -6 has position 1 and 3.4 has position 2.

Since the order of items in [1, 2, 3] and [2, 1, 3] are not the same, they are not equal.

Lists allow duplicate items

An item can be present multiple times in a list. This is opposite to python sets where all items are unique.

In the above, position 1, 3 and 4 have the same values 9.8, still they are distinct elements of the list.

Lists are heterogeneous

A list can contain items or elements that are of different data-types.

The above list contains 'float, 'str' and 'int' type objects. A list can even contain another list, tuple, set, dictionary or string.

Lists are mutable

A list is a mutable object. Any time we can change an item or range of items of a list. We can even add, remove, insert, sort items of a list.

Lists are slower

Lists are slower in comparison to the other data-structures like tuple and sets. This is due to the mutable and heterogeneous properties of lists. Duplicate values of a large list may also cause slower operation.

What are iterables?

An iterable is an object which can be iterated over. List, tuples, dictionaries, sets and strings are iterable objects.

Take the example of a list. It is a collection that contains multiple items. We can iterate over a list and can access one item at a time. Each iteration will return the next value of the iterable until the end is reached.

The process of iteration is performed by an iterator, which is created by the iter(iterable) function. In an iteration, when no item is left, a StopIteration error is raised.

Create list from iterables

The list() function can be used to create a list from iterables like 'str', 'tuple' etc.

In the above, two lists have been generated from a string object "python", and a tuple object (1, 2, 3).

A set object and a dictionary object have been converted to two lists.

Length of a list: len() function

Python len() function is used to find the length of an object. When the argument is a list object, len(list) simply returns the length of the given list. In other words, the number of items in the list is returned.

An empty list has a zero length. Note that the data-type of variable length is 'int'.

List Indexing

Normally, we require three separate variables to hold three python objects. But, in the following, a single list variable x points to three objects 3.1415, "python" and 42. The objects it points to are called items or elements or members of the list.

A python list of three items x = type 'list' length = 3 3.1415 python 42 x[0] x[1] x[2] items 'float' 'str' 'int' 0 1 2 index

Access an item by its index

Every item of a list has an index. An index is an integer inside a pair of square brackets that is placed immediately after the list variable; for example, x[0]. The index of the first item of a list is always zero.
An item of a list can be accessed by the index of that item.

x[0] points to the 1st item 3.1415,
x[1] points to the 2nd item "python",
x[2] points to the 3rd item 42.
Calling x[3] will raise an IndexError because there is no 4rth item.

We can see that variable x is of type 'list'. But types of x[0], x[1] and x[2] are 'float', 'str' and 'int' respectively.
They are also independent variables, and can take part in any calculations.

Negative indexing

An index may be negative too. Index -1 always points to the last item of a list. The first item of a list can be accessed with the index -len(x)

x = 3.1415 python 42 0 1 2 -3 -2 -1

x[0] and x[-3] are the same, x[1] and x[-2] are the same, x[2] and x[-1] are the same.
All of the following equality comparisons and identity comparisons return True:

Nested lists

A python list can contain another list. Consider the following assignment:

In the above, the list [8, 9] itself is an element of another list n. Its index is 1. When we access n[1], we get this inner list as a result.

n = 10 [8, 9] 5.77 0 1 2 -3 -2 -1

Note that the inner list [8, 9] is a single unit/item. If we check len(n), length will be 3, not 4.
Also if we reverse list n, items inside the inner list remain in the same order.

Since n[1] refers to the inner list [8, 9],
n[1][0] refers to the first item of it, and n[1][1] refers to the second item.

Nested List 10 8 9 5.77 n[0] n[1] n[2] n[1][0] n[1][1]

Modifying a list

Python lists are mutable objects. We can modify individual items of a list with assignment statements.

We targeted the third item of the list, and assigned it a boolean literal. Note that the data-type of x[2] has changed from 'int' to 'bool'.

Elements/items of strings or tuples cannot be modified in this way because they are immutables.

Python lists can also be modified through slice assignment, as well as using list methods which have been detailed in respective pages.

The del statement with list item

The del statement can be used to remove an item from the list.

Membership with list

Python membership operators in and not in can be used to check whether an item is a member of a list or not.

Since the item "Delhi" is a member of the list cities, the membership expression "Delhi" in cities returns True. "Kolkata" is also a member of the list, so the expression "Kolkata" not in cities returns False.

Unpacking a list

In python, the list unpacking feature enables us to assign a single list to multiple variables.

We have to remember that the number of variables in the left side must match the number of items in the assigned list.

Python provides special unpacking with the * (asterisk) and _ (underscore) operators which will be discussed in a separate article.

List concatenation

The concatenation operator + can join two lists producing a new list.

Note that the given lists p and q remain unchanged..

The augmented assignment operator += can also be used to join two lists.

Note that list var1 is modified by augmentation, but var2 remains the same.

List repetition

The use of repetition operator * repeats the items of a list.

In this case, one of the right side operands must be a list, while the other operand must be an integer.

    # Summary

  • 01 Python lists are ordered collection of heterogeneous items.
  • 02 Lists are mutable objects, they are modifiable.
  • 03 List index is zero-based.
  • 04 Every item has its own position(index).
  • 05 A list item is accessible by its index.

--- x ---

Want to leave a message for me?