The Python List is a general data structure widely used in Python programs. They are found in other languages, often referred to as dynamic arrays. They are both mutable and a sequence data type that allows them to be indexed and sliced. The list can contain different types of objects, including other list objects.
- [value, value, ...]
list is the name given in Python to dynamic arrays (similar to
vector<void*> from C++ or Java's
ArrayList<Object>). It is not a linked-list.
Accessing elements is done in constant time and is very fast. Appending elements to the end of the list is amortized constant time, but once in a while it might involve allocation and copying of the whole
List comprehensions are related to lists.
Accessing list values
Python lists are zero-indexed, and act like arrays in other languages.
Attempting to access an index outside the bounds of the list will raise an
Negative indices are interpreted as counting from the end of the list.
This is functionally equivalent to
Lists allow to use slice notation as
lst[start:end:step]. The output of the slice notation is a new list containing elements from index
end-1. If options are omitted
start defaults to beginning of list,
end to end of list and
step to 1:
With this in mind, you can print a reversed version of the list by calling
When using step lengths of negative amounts, the starting index has to be greater than the ending index otherwise the result will be an empty list.
Using negative step indices are equivalent to the following code:
The indices used are 1 less than those used in negative indexing and are reversed.
When lists are sliced the
__getitem__() method of the list object is called, with a
slice object. Python has a builtin slice method to generate slice objects. We can use this to store a slice and reuse it later like so,
This can be of great use by providing slicing functionality to our objects by overriding
__getitem__ in our class.
Accessing values in nested list
Starting with a three-dimensional list:
Accessing items in the list:
Performing support operations:
Using nested for loops to print the list:
Note that this operation can be used in a list comprehension or even as a generator to produce efficiencies, e.g.:
Not all items in the outer lists have to be lists themselves:
Another way to use nested for loops. The other way is better but I've needed to use this on occasion:
Using slices in nested list:
The final list:
Any and All
You can use
all() to determine if all the values in an iterable evaluate to True
any() determines if one or more values in an iterable evaluate to True
While this example uses a list, it is important to note these built-ins work with any iterable, including generators.
Checking if list is empty
The emptiness of a list is associated to the boolean
False, so you don't have to check
len(lst) == 0, but just
Checking whether an item is in a list
Python makes it very simple to check whether an item is in a list. Simply use the
inoperator on sets is asymptotically faster than on lists. If you need to use it many times on potentially large lists, you may want to convert your
set, and test the presence of elements on the
Comparison of lists
It's possible to compare lists and other sequences lexicographically using comparison operators. Both operands must be of the same type.
If one of the lists is contained at the start of the other, the shortest list wins.
Concatenate and Merge lists
The simplest way to concatenate
zipreturns a list of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables:
If the lists have different lengths then the result will include only as many elements as the shortest one:
For padding lists of unequal length to the longest one with
itertools.izip_longestin Python 2)
Insert to a specific index values:
Initializing a List to a Fixed Number of Elements
For immutable elements (e.g.
None, string literals etc.):
For mutable elements, the same construct will result in all elements of the list referring to the same object, for example, for a set:
Instead, to initialize the list with a fixed number of different mutable objects, use:
Iterating over a list
Python supports using a
for loop directly on a list:
You can also get the position of each item at the same time:
The other way of iterating a list based on the index value:
Note that changing items in a list while iterating on it may have unexpected results:
In this last example, we deleted the first item at the first iteration, but that caused
bar to be skipped.
Length of a list
len() to get the one-dimensional length of a list.
len() also works on strings, dictionaries, and other data structures similar to lists.
len() is a built-in function, not a method of a list object.
Also note that the cost of
O(1), meaning it will take the same amount of time to get the length of a list regardless of its length.
List methods and supported operators
Starting with a given list
append(value)– appends a new element to the end of the list.
Note that the
append()method only appends one new element to the end of the list. If you append a list to another list, the list that you append becomes a single element at the end of the first list.
extend(enumerable)– extends the list by appending elements from another enumerable.
Lists can also be concatenated with the
+operator. Note that this does not modify any of the original lists:
index(value, [startIndex])– gets the index of the first occurrence of the input value. If the input value is not in the list a
ValueErrorexception is raised. If a second argument is provided, the search is started at that specified index.
insert(index, value)– inserts
valuejust before the specified
index. Thus after the insertion the new element occupies position
pop([index])– removes and returns the item at
index. With no argument it removes and returns the last element of the list.
remove(value)– removes the first occurrence of the specified value. If the provided value cannot be found, a
reverse()– reverses the list in-place and returns
There are also other ways of reversing a list.
count(value)– counts the number of occurrences of some value in the list.
sort()– sorts the list in numerical and lexicographical order and returns
Lists can also be reversed when sorted using the
reverse=Trueflag in the
If you want to sort by attributes of items, you can use the
In case of list of dicts the concept is the same:
Sort by sub dict :
Better way to sort using
Lists can also be sorted using
itemgetter functions from the operator module. These can help improve readability and reusability. Here are some examples,
itemgetter can also be given an index. This is helpful if you want to sort based on indices of a tuple.
attrgetter if you want to sort by attributes of an object,
clear()– removes all items from the list
Replication – multiplying an existing list by an integer will produce a larger list consisting of that many copies of the original. This can be useful for example for list initialization:
Take care doing this if your list contains references to objects (eg a list of lists), see Common Pitfalls - List multiplication and common references.
Element deletion – it is possible to delete multiple elements in the list using the
delkeyword and slice notation:
The default assignment "=" assigns a reference of the original list to the new name. That is, the original name and new name are both pointing to the same list object. Changes made through any of them will be reflected in another. This is often not what you intended.
If you want to create a copy of the list you have below options.
You can slice it:
You can use the built in list() function:
You can use generic copy.copy():
This is a little slower than list() because it has to find out the datatype of old_list first.
If the list contains objects and you want to copy them as well, use generic copy.deepcopy():
Obviously the slowest and most memory-needing method, but sometimes unavoidable.
copy() – Returns a shallow copy of the list
Remove duplicate values in list
Removing duplicate values in a list can be done by converting the list to a
set (that is an unordered collection of distinct objects). If a
list data structure is needed, then the set can be converted back to a list using the function
Note that by converting a list to a set the original ordering is lost.
To preserve the order of the list one can use an
Reversing list elements
You can use the
reversed function which returns an iterator to the reversed list:
Note that the list "numbers" remains unchanged by this operation, and remains in the same order it was originally.
To reverse in place, you can also use the
You can also reverse a list (actually obtaining a copy, the original list is unaffected) by using the slicing syntax, setting the third argument (the step) as -1: