Sequences
2026-08-01
Data structures that other languages call collections or containers, Python calls sequences, and provides several built-in sequences like list, which is a mutable sequence; tuple, which is an immutable sequence; dict, which is a key-value pair mapping; str, which is a sequence of characters; and sets of unique keys.
All sequences are iterable, i.e., they support the iter and next build-in functions. This means their items can be accessed one-by-one. Many standard sequences support some common operations, while mutable supports more, and can perform operations directly on the items (in-place).
List
The list type represents a flexible and mutable sequence. An object of type list can be created in several ways, and each item is a reference to any object, including other lists.
List Creation
Objects of type list can be created by function call, or by using list literals.
List Type Function
Like all type functions, list can create a list object from any iterable expression (iter-expr). When passed no arguments, it returns an empty sequence.
list( [ iter-expr ] )
py — Create lists with the list function
L1 = list() #← empty list.
L2 = list("ABC") #← L2 = ['A', 'B', 'C']
L3 = list(range(5)) #← L3 = [0, 1, 2, 3, 4]
print(type(L1)) #→ class listList Literals
We can also create a list object using a list literal, which is a set of square brackets delimiting zero or more items (expressions), separated by a comma (,). A trailing comma is allowed. The types of the items do not have to be the same, since each item is a reference to an object.
py — Create lists with list literals
L1 = [] #← empty list.
L2 = ["A", "B", "C"]
L3 = [11, 22.33, "STRING"] #← `int`, `float` and `str`.
print(L1, L2, L3)[] ['A', 'B', 'C'] [11, 22.33, 'STRING']
As with all types, list objects are convertible to string, implicitly, or explicitly. When converted to a string, the representation will surround the items with square brackets, with the items separated by commas.
List items can reference any type of object, even other lists.
py — Lists of lists
L1 = [11, 22]
L2 = [33, 44, 55]
L3 = [L1, L2, [66, 77], "ABC", ]
print(f"L3={L3}")L3=[[11, 22], [33, 44, 55], [66, 77], 'ABC']
As can be seen with L3, a trailing comma is a allowed as a matter of convenience. This is especially useful when the list literal spans several lines.
py — List literals spanning lines
L1 = [
"First item",
"Second item",
"Third item",
]Leading spaces are not relevant, and the trailing comma makes it easy to add more items. The indentation level of the closing square bracket delimiter, is also not significant. The following example is entirely legal, but not recommended:
py — Legal but ‘ugly’ indentation
if True:
L1 = [
"First item",
"Second item",
"Third item",
]
print(L1)Syntax-wise, it is only important for L1 and print to be consistently indented. But, the code above is difficult for humans to read and understand.
Empty Lists
An empty list when converted to boolean, will return False. Any other value, will produce True. This is useful with the if statement, where ‘if list-expr:’ becomes an abstraction for ‘if the list-expr is non-empty…’.
py — Empty list abstraction
print(bool([])) #→ False
print(bool(list())) #→ False
L1 = []
if L1:
print("List is not empty")
else
print("List is empty")
print(bool(L1)) #→ FalseThis is more idiomatic than: ‘if len(list-obj) == 0:’.
Tuple
The tuple built-in function creates immutable sequences — once created, they cannot be modified. Operations on tuples, create copies. Objects of type tuple can also be created with literals.
Tuple Creation
We can create objects of type tuple using the function, or using a tuple literal.
Tuple Function
Calling the tuple function without arguments, will create an emtpy tuple (len is 0). Alternatively, it will accept any iterable expression as argument. For a literal with one item, a trailing comma is required.
py — Create tuple with tuple function
T1 = tuple() #← empty tuple.
T2 = tuple("ABC") #← T2=('A','B','C')
T3 = tuple(range(6)) #← T3=(0,1,2,3,4,5)When a tuple is converted to a string, the items are separated with a comma, and they will all be surrounded by parentheses.
Tuple Literals
A literal tuple can be surrounded by parentheses, but because parentheses are also used for arithmetic grouping, and function calls, Python uses other heuristics to determine if a literal is a tuple. Here, the comma separating items, becomes important.
py — Create tuples with tuple literals
T1 = () #← empty tuple literal.
T2 = (11, 22, 33) #← parentheses optional.
T3 = 11, 22, 33 #← equivalent to above.
T4 = (11, 22, 33,) #← trailing comma OK.
T4 = 11, 22, 33, #← trailing comma also OK.
T5 = (11) #← NOT A TUPLE.
T6 = (11,) #← tuple with one item.
T7 = 11, #← tuple with one item.
T8 = (11, #← parentheses required.
22, #
33,) #In the last statement the parentheses are required; the trailing comma is still optional. Passing a tuple literal as an argument also requires the parentheses:
py — Pass tuple literal as argument
def func (param): print(f"param={param})
func(11, 22, 33) #← ERROR
func((11, 22, 33)) #→ param=(11, 22, 33)As with Lists, the items in a tuple, can be any type, including other tuples, lists, other sequences (whose items can reference other sequences, …, and so on).
py — Complex tuple literals
T1 = 11, 22
T2 = 55,
T3 = (T1, [33, 44], (T2, 66))
print("T3 =", T3)T3 = ((11, 22), [33, 44], ((55,), 66))
A tuple supports all the common sequence operations, but not the mutable operations. New tuples can be created with the overloaded + (concatenation) and * (repetition) operators, both can be used in augmented assignments: += and *=.
Sequence Operations
As list, tuple supports similar operations, we focus on these operations applied to the sequences in general.
Sequence Length
The built-in len indirectly calls a special __len__ method, which is implemented in list and other sequence objects to return the number of items in the sequence. An empty sequence will have a length of 0.
py — Number of items in sequences
L1 = [ 11, [ 22, 33, ], 44, [ 55, 66, ], ]
print("L1 #items =", len(L1)) #→ L1 #items = 4
print(len([11, 22, 33, 44, 55, 66])) #→ 6
print(len([])) #→ 0
L2 = []
print(len(L2)) #→ 0
T1 = ( 11, [ 22, 33, ], 44, [ 55, 66, ], )
print("T1 #items =", len(T1)) #→ T1 #items = 4
T2 = tuple() #← empty tuple.
print(len(T2)) #→ 0Note that L1 and T1 both contain only 4 items, not 6. Two of the four items are lists. Each item is just a reference to some type of object.
Sequence Subscript
Individual items in any sequence can be accessed with the postfix subscript operator applied to a seq-object: seq-obj[ expr ]. The expression between the square brackets, is the index of the item to access; which ranges from 0 (first item) to ‘len(seq-obj) - 1’ (last item). An out of range index will result in raising a IndexError exception.
py — Sequence subscript index range
L = [11, 22, 33, 44]
print(L[0], L[1], L[2], L[3], L[len(L)-1]) #→ 11 22 33 44 44
T = (11, 22, 33, 44)
print(T[0], T[1], T[2], T[3], T[len(L)-1]) #→ 11 22 33 44 44 Note that L[3] and T[3] results in 44, which is the last item. The same result can be obtained with: L[len**(L1)-1], for example. The number of items in L** and T, is 4.
Negative indexes on a sequence: ‘[ -index ]’, are allowed as a convenient shorthand for: ‘[ len(list-obj) - index ]’.
py — Negative sequence subscript indexes
S = [11, 22, 33, 44] #→ or: `S = ( ··· )`
print(S[ 0], S[ 1], S[ 2], S[ 3]) #→ 11 22 33 44
print(S[-4], S[-3], S[-2], S[-1]) #→ 11 22 33 44
print(S[-1], S[-2], S[-3], S[-4]) #→ 44 33 22 11
print(S[len(S)-1], end=" ") #→ 44
print(S[len(S)-2], end=" ") #→ 33
print(S[len(S)-3], end=" ") #→ 22
print(S[len(S)-4]) #→ 11It should be apparent that any item in a sequence can be referenced using either a positive, or a negative, index.
The subscript operator is convenient shorthand for calling the special __setitem__ and __getitem__ methods present in all sequences.
List Modification
Since lists are mutable, we can modify the values in such an object. We can overwrite existing references, add new items, or even delete items. This is not possible for tuples.
py — Modifying lists items
L = [ 11, 22, 33, 44, 55 ]
print(L) #→ [11, 22, 33, 44, 55]
L[2] = 99 #← assignment statement.
print(L) #→ [11, 22, 99, 44, 55]
del L[2] #← delete statement.
print(L) #→ [11, 22, 44, 55]Note that del is a statement, not a built-in function.
In order to add more items to a list, we can use ‘list-obj.append(item)’ to append a single item; or ‘list-obj.extend(iterable)’ to append multiple items. Both add items at the end of the list. Think of append as ‘pushing’ items onto the list; the corresponding ‘list-obj.pop()’, will remove the last item.
py — Appending and removing list items
L1 = [ 1, 2, 3, 4, 5, 6, 7 ] #← L1=[1,2,3,4,5,6,7]
L1.pop() ; L1.pop() ; L1.pop() #← L1=[1,2,3,4]
L1.append(5) #← L1=[1,2,3,4,5]
L1.extend(L2) #← L1=[1,2,3,4,5,6,7]Sequence Concatenation
The plus operator (+) applies to all sequences. It will concatenate two sequences of the same type, resulting in a new sequence. It also works with augmented assignment (+=).
py — Sequence concatenation
S1 = [ 11, 22 ]
S1 = S1 + S1 + S1
print(S1) #→ [11,22, 11,22, 11, 22]
S1 = [ 11, 22 ]
S1 += [ 33, 44, 55 ]
print(S1) #→ [11,22,33,44,55]
S1 = ( 11, 22 )
S1 += S1 + S1
print(S1) #→ (11,22, 11,22, 11,22)Sequence Repetition
Any sequence can be repeated count times using the asterisk (*) operator, where count is an integer expression that can appear on the left or right of the asterisk. The other operand must be a sequence.
py — Sequence repetition
L = [11, 22]
print(L * 3) #→ [11,22, 11,22, 11,22]
print(3 * L) #→ [11,22, 11,22, 11,22]
N = 3 ; L *= N
print(L) #→ [11,22, 11,22, 11,22]
print((11, 22) * N) #→ (11,22, 11,22, 11,22)
print(N * (11, 22)) #→ (11,22, 11,22, 11,22)
print("ABC" * N) #→ ABCABCABC
print(N * "ABC") #→ ABCABCABCOther Operations
The list-obj.clear method will empty the list, and the list-obj.copy method will make a shallow copy. The list-obj.insert method can insert an new item at a given index.
The list-obj.index, list-obj.count and list-obj.remove, all accept item values; where index will return the first index where a value is found; count will count the number of items equal to a value; and remove will delete the first item with that value.
The list-obj.sort method will perform an in-place ordering of the items based on their values. The list-obj.reverse method will reverse all the items in-place. The sorted and reverse built-ins will make copies of a list object, unlike the corresponding methods.
Other built-in functions also accept iterables, like sum, min and max. The sum method will only work in numeric types, while the other two will only work with object types that implement special __min__ and __max__ methods.
The overloaded asterisk (*) will repeat a list count number of times, where count must be an integer expression. The count can be on the left hand side, or right hand side, of the asterisk: ‘list-obj * count’ ‖ ‘count * list-obj’.