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