A list in Python represents a collection of ordered items. The items can be of varying types such as numbers, strings and even other lists, literally anything that has value can be stored in a list.
Lists are mutable, which means that we can modify them in-place after they are created. In contrast, immutable types like strings and tuples require the creation of a new object in memory each time they are modified. This makes mutable objects more flexible and memory efficient, allowing for faster and more complex data manipulation.
Lists objects are created by enclosing comma separated items in square brackets []. The following examples demonstrates this.
An empty list:
[]
copy
A list of integers:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
copy
A list of strings:
["America", "China", "Australia", "Brazil", "South Africa"]
copy
A list of lists:
[ [1, 2, 3], [4, 5, 6], [7, 8, 9] ]
copy
A list of mixed types:
[ 1, "Python", [1, 2, 3], ('Python', 'Javascript', 'Html', 'CSS') ]
copy
As shown above, one way to create an empty list is to simply use empty square brackets, another way to achieve this is by using the builtin list()
function.
This function can also be used to cast other relevant types into lists.
Operations on Lists.
A wide variety of operations can be performed on lists, thanks to their mutable nature, which allows for efficient in-place modifications. This means that the majority of these operations directly modify the original list rather than creating a new one. We will explore some of the most common list operations.
Concatenation and Repetition
The " + " operator is used in list concatenation. In this operation, all the elements of the second list operand are appended to the end of the first list.
In list repetition, the " * " operator is used with a list operand and an integer operand. The resulting list contains elements which are the original list's elements repeated the number of times specified by the integer operand.
If 0 is used as the integer operand, the repetition will result in an empty list.
List repetition is especially used to initialize lists with default values.
Indexing, Slicing and Assignment
Each Element in a list has an index through which it can be accessed. The first element in the list has an index 0 , the second has an index 1 , and so forth. Lists like other sequences also support negative indexing, in this case, the last element in the list has an index -1 , the second last has -2, the third from last has -3 and so forth.
The length of a list is equal to number of items that it contains. We can use the builtin len()
function to get the list's length, as shown below:
If a list has a length L, the valid indices including negative and positive indices starts from -L and ends at L - 1 . Using an index out of this range will result in an IndexError
.
Square braces []
are used to access the element at a given index. For example if we have a list L , the syntax is as follows:
L[index]
copy
Accessing the first element.
Accessing the last Element.
accessing elements using positive indexing:
Accessing elements using negative indexing:
As we said earlier, using an index outside the valid indices ( -L to L-1 ) will raise an IndexError
:
Slicing
While indexing is used to access the element at a specific index, slicing is used to access all the elements in a given range of indices, a list containing these elements is returned.
The square brackets are still used in slicing, but with a slightly different syntax in order to capture a range. The syntax is as follows;
L[start : stop : step]
copy
All the three arguments, start, stop, and step are integers. The start indicates the index where the slicing will begin, the stop indicates the index where the slicing will end without itself included, and the step indicates the jump value. If any of the arguments are omitted, they take on default values: start
defaults to 0, stop
defaults to the length of the list , and step
defaults to 1.
Assignment
Since lists are mutable we can change the value at a given index or slice using assignment. The syntax is as follows:
L[index] = <new value> L[slice] = <new value>
copy
Doing this overwrites the value at the given index or slice with the new value. If we use slice for assignment, the new value needs to be an iterable such as another list, tuple, set e.t.c.
Index assignment Examples:
Slice assignment Examples:
Trying to assign on an invalid index or slice will raise an IndexError
.
List Methods
The list
class offers a variety of practical methods that can be invoked on any list instance. Let us look at some of these methods.
append()
Syntax:
L.append(item)
copy
This method is used to add an item to the end of the list.
clear()
Syntax:
L.clear()
copy
Removes all elements from the list, effectively making it an empty list.
copy()
Syntax:
L.copy()
The copy()
method in creates a shallow copy of the list. This means that a new list object is created with the same elements as the original list, but any mutable elements in the original list (such as lists or dictionaries) are still referenced by both the original and the copied list.
extend()
Syntax:
L.extend(iter)
copy
Adds all elements of an iterable iter (e.g. another list) to the list L.
index()
Syntax:
L.index(x)
copy
Returns the position (index) of the leftmost occurrence of value x in the list L, raises a ValueError
if the item is not in the list.
insert()
Syntax:
L.insert(i, x)
Inserts element x at position (index) i in the list L.
pop()
Syntax:
L.pop(i)
copy
Removes and returns the element at index i, if i is not given it defaults to the last index of the list L .
remove()
Syntax:
L.remove(x)
copy
Removes the leftmost occurrence of element x in the list L, raises ValueError
if x is not in the list.
reverse()
Syntax:
L.reverse()
copy
Reverses the order of elements in the list L.
sort()
Syntax:
L.sort()
copy
Sorts the elements in the list L in ascending order.