Python Sequence Types
Python sequence types are predefined iteration objects. The basic sequence types are lists, tuples, and range objects.
Python Sequence Operations
Common Sequence Operations
Common sequence operations are most typical operations supported sequence types, both mutable and immutable.
The collections.abc.Sequence ABC is provided to make it easier to correctly implement these operations on custom sequence types.
This table lists the sequence operations sorted in ascending priority. In the table, s and t are sequences of the same type, n, i, j and k are integers and x is an arbitrary object that meets any type and value restrictions imposed by s.
The in and not in operations have the same priorities as the comparison operations. The + (concatenation) and * (repetition) operations have the same priority as the corresponding numeric operations. 3
OperationDescriptionRemarks
𝑥 in 𝑠Return True if 𝑥 is equal to one of the elements in container 𝑠, else return False
𝑥 not in 𝑠Return False if 𝑥 is equal to one of the elements in container 𝑠, else return True
𝑠+𝑡Return the concatenation of elements of 𝑠 and 𝑡 accordingly
𝑠*𝑛, or 𝑛*𝑠Return the adding of elements in container 𝑠 to itself 𝑛 times
𝑠[𝑖]Return the 𝑖th element of zero based container 𝑠.
𝑠[𝑖:𝑗]Return the slice from 𝑖th element to 𝑗th element of zero based container 𝑠.
𝑠[𝑖:𝑗:𝑘]Return the slice from 𝑖th element to 𝑗th element with step 𝑘 of zero based container 𝑠.
len(𝑠)Return the length of elements in container 𝑠
min(𝑠)Return the smallest element of 𝑠
max(𝑠)Retrun the largest element of 𝑠
𝑠.index(𝑥[,𝑖[,𝑗]])Return the first occurrence of element 𝑥 in container 𝑠 with option at or after index 𝑖 and before index 𝑗.
𝑠.count(𝑥)Return the total number of occurrences of 𝑥 in container 𝑠.
Sequences of the same type also support comparisons. In particular, tuples and lists are compared lexicographically by comparing corresponding elements. This means that to compare equal, every element must compare equal and the two sequences must be of the same type and have the same length. (For full details see Comparisons in the language reference.)
Notes:
While the in and not in operations are used only for simple containment testing in the general case, some specialised sequences (such as str, bytes and bytearray) also use them for subsequence testing:
>>>
>>> "gg" in "eggs"
True
Values of n less than 0 are treated as 0 (which yields an empty sequence of the same type as s). Note that items in the sequence s are not copied; they are referenced multiple times. This often haunts new Python programmers; consider:
>>>
>>> lists = [[]] * 3
>>> lists
[[], [], []]
>>> lists[0].append(3)
>>> lists
[[3], [3], [3]]
What has happened is that [[]] is a one-element list containing an empty list, so all three elements of [[]] * 3 are references to this single empty list. Modifying any of the elements of lists modifies this single list. You can create a list of different lists this way:
>>>
>>> lists = [[] for i in range(3)]
>>> lists[0].append(3)
>>> lists[1].append(5)
>>> lists[2].append(7)
>>> lists
[[3], [5], [7]]
Further explanation is available in the FAQ entry How do I create a multidimensional list?.
If i or j is negative, the index is relative to the end of sequence s: len(s) + i or len(s) + j is substituted. But note that -0 is still 0.
The slice of s from i to j is defined as the sequence of items with index k such that i <= k < j. If i or j is greater than len(s), use len(s). If i is omitted or None, use 0. If j is omitted or None, use len(s). If i is greater than or equal to j, the slice is empty.
The slice of s from i to j with step k is defined as the sequence of items with index x = i + n*k such that 0 <= n < (j-i)/k. In other words, the indices are i, i+k, i+2*k, i+3*k and so on, stopping when j is reached (but never including j). When k is positive, i and j are reduced to len(s) if they are greater. When k is negative, i and j are reduced to len(s) - 1 if they are greater. If i or j are omitted or None, they become “end” values (which end depends on the sign of k). Note, k cannot be zero. If k is None, it is treated like 1.
Concatenating immutable sequences always results in a new object. This means that building up a sequence by repeated concatenation will have a quadratic runtime cost in the total sequence length. To get a linear runtime cost, you must switch to one of the alternatives below:
if concatenating str objects, you can build a list and use str.join() at the end or else write to an io.StringIO instance and retrieve its value when complete
if concatenating bytes objects, you can similarly use bytes.join() or io.BytesIO, or you can do in-place concatenation with a bytearray object. bytearray objects are mutable and have an efficient overallocation mechanism
if concatenating tuple objects, extend a list instead
for other types, investigate the relevant class documentation
Some sequence types (such as range) only support item sequences that follow specific patterns, and hence don’t support sequence concatenation or repetition.
index raises ValueError when x is not found in s. Not all implementations support passing the additional arguments i and j. These arguments allow efficient searching of subsections of the sequence. Passing the extra arguments is roughly equivalent to using s[i:j].index(x), only without copying any data and with the returned index being relative to the start of the sequence rather than the start of the slice.
Sequence Operation for Immutable Sequence Types
The only operation that immutable sequence types generally implement that is not also implemented by mutable sequence types is support for the hash() built-in.
This support allows immutable sequences, such as tuple instances, to be used as dict keys and stored in set and frozenset instances.
Attempting to hash an immutable sequence that contains unhashable values will result in TypeError.
Sequence Operation for Mutable Sequence Types
The operations in the following table are defined on mutable sequence types. The collections.abc.MutableSequence ABC is provided to make it easier to correctly implement these operations on custom sequence types.
In the table s is an instance of a mutable sequence type, t is any iterable object and x is an arbitrary object that meets any type and value restrictions imposed by s (for example, bytearray only accepts integers that meet the value restriction 0 <= x <= 255).
OperationDescriptionRemarks
𝑠[𝑖]=𝑥to replace the 𝑖th element of the zero based container 𝑠 by 𝑥
𝑠[𝑖:𝑗]=𝑡to replace the slice of zero based container 𝑠 from 𝑖th element to 𝑗th element by all elements of the iterable 𝑡.
del 𝑠[𝑖:𝑗]to delete the slice of zero based container 𝑠 from 𝑖th element to 𝑗th element. Same as [𝑖:𝑗]=[]
𝑠[𝑖:𝑗:𝑘]=𝑡to replace the slice of zero based container 𝑠 from 𝑖th element to 𝑗th element with step 𝑘 by all elements of the iterable 𝑡.
del 𝑠[𝑖:𝑗:𝑘]to delete the slice of zero based container 𝑠 from 𝑖th element to 𝑗th element with step 𝑘. Same as [𝑖:𝑗:𝑘]=[]
𝑠.append(𝑥)to append 𝑥 to the end of the zero based container 𝑠. Same as 𝑠[len(𝑠):len(𝑠)]=[𝑥]
𝑠.clear()to remove all elements from 𝑠. Same as del 𝑠[:]
𝑠.copy()to return a shallow copy of 𝑠, which is same as 𝑠[:]
𝑠.extend(𝑡) or 𝑠+=𝑡to extends 𝑠 with the elements of the iterable 𝑡. For the most part the same as 𝑠[len(𝑠):len(𝑠)]=𝑡
𝑠*=𝑛to append 𝑠 by repeating 𝑛 times of all elements in container 𝑠
𝑠.insert(𝑖,𝑥)to insert item 𝑥 into zero based container 𝑠 at the index 𝑖. Same as 𝑠[𝑖:𝑖]=[𝑥]
𝑠.pop([𝑖])to return and remove the 𝑖th element of zero based container 𝑠.
𝑠.remove(𝑥)to remove the first equal to 𝑥 element of zero based container 𝑠
𝑠.reverse()to reverse the elements of zero based container 𝑠 in place.
Notes:
t must have the same length as the slice it is replacing.
The optional argument i defaults to -1, so that by default the last item is removed and returned.
remove() raises ValueError when x is not found in s.
The reverse() method modifies the sequence in place for economy of space when reversing a large sequence. To remind users that it operates by side effect, it does not return the reversed sequence.
clear() and copy() are included for consistency with the interfaces of mutable containers that don’t support slicing operations (such as dict and set). copy() is not part of the collections.abc.MutableSequence ABC, but most concrete mutable sequence classes provide it.
New in version 3.3: clear() and copy() methods.
The value n is an integer, or an object implementing __index__(). Zero and negative values of n clear the sequence. Items in the sequence are not copied; they are referenced multiple times, as explained for s * n under Common Sequence Operations.
Source and Reference