Sequences

Table of Contents

1. Sequences

A sequence in Python is a type of ordered collection that contains items arranged in order, which you can access by using an integer index. Examples of sequences include lists and tuples.

Sequences have the following characteristics:

  1. A sequence is iterable, which means you can iterate through it.
  2. You can use the function len() to find the length of a sequence.
  3. An element of a sequence can be accessed using an index based on its position in the sequence.
  4. You can use in to perform membership testing.
  5. You can use colon and bracket syntax to perform slicing.

1.1. Length

Every sequence has a length, which can be found by applying the function len() to the sequence:

digits = [1, 2, 3, 4]
assert 4 == len(digits)

1.2. Indexing

Every sequence can be indexed using bracket notation. Sequences are zero-indexed, which means the first element in a sequence is assigned the index 0, the second is 1, and so on:

digits = [1, 2, 3, 4]
assert 4 == digits[3]

1.3. in Operator

The built-in operator in tests whether an element appears in a compound value:

digits = [1, 8, 2, 8]
assert 1 in digits          # True
assert 'here' in 'Where'    # True

1.4. Slicing

We can slice a sequence to obtain a sub-sequence of that sequence. For example, the expression s[1:] is a slice from index 1 to the end of s, containing all the elements of s except s[0].

More formally, a slice s[a:b] returns a sub-sequence of s starting from the index a and up to but not including the index b. We can also leave out a or b as shorthand to represent the beginning or the end of the list, respectively. Slicing will always create new values.

1.5. Sequence Aggregation

The function sum(iterable[, start]) -> value returns the sum of an iterable of numbers (not strings) plus the value of parameter start (which defaults to 0). When the iterable is empty, return start:

a = sum([2, 3, 4])          # 9
b = sum([2, 3, 4], 5)       # 14
c = sum([[2, 3], [4]], [])  # [2, 3, 4]

The function max(iterable[, key=func]) -> value and max(a, b, c, ...[, key=func]) -> value returns either the largest element in the iterable, or the largest argument with two or more arguments. The key function allows you to customize how the maximum value is determined by applying a function to each element before comparison:

d = max(range(5))           # 4
s = ['a', 'aaa', 'aa']
longest = max(s, key=len)   # 'aaa'

The function all(iterable) -> bool returns True if bool(x) is True for all values x in the iterable. If the iterable is empty, return True. The bool function converts an expression to a boolean by evaluating it to either a True or False value.

trues = [True, True, True]
istrue = all(trues)         # True

Similarly, the function any(iterable) -> bool returns True if bool(x) is True for any value in the iterable. If the iterable is empty, return False.

some = [True, False, False]
istrue = any(some)          # True

Similar to

2. Lists

A list is a type of sequence which can be of different data types. Lists are mutable, meaning you can modify them by adding, removing, or changing elements. We can define a list using literals like so:

digits = [1, 8, 2, 8]

We can also concatenate or repeat lists by using the addition and multiplication operators:

assert [1, 2, 3, 4] == [1, 2] + [3, 4]
assert [1, 1, 1, 1] == [1] * 4

We can nest lists like so:

pairs = [[10, 20], [30, 40]]
assert [10, 20] == pairs[0]

We can mutate lists:

suits = ['coin', 'string', 'myriad']
original_suits = suits
s = suits.pop()                           # 'myriad', suits is now ['coin', 'string']
suits.remove('string')                    # suits is now ['coin']
suits.append('cup')                       # suits is now ['coin', 'cup']
suits.extend(['sword', 'club'])           # suits is now ['coin', 'cup', 'sword', 'club']
suits[2] = 'spade'                        # suits is now ['coin', 'cup', 'spade', 'club']
suits[0:2] = ['heart', 'diamond']         # suits is now ['heart', 'diamond', 'spade', 'club']
# original_suits is also ['heart', 'diamond', 'spade', 'club']

We can also sum the integers in a list, and also lists within lists:

a = sum([1, 2, 3])           # 6
b = sum([[1], [2, 3], [4]], [])  # [1, 2, 3, 4]

Notice that when you sum a list of lists with a list, it just removes one level of the list.

2.1. List Comprehension

We can use a list comprehension to build a list using the following syntax:

newlist = [<expression> for <item> in <iterable> if <condition>]

The <condition> is optional and may be omitted. What this syntax does is to form a list, applying the <expression> on each <item> in an <iterable> if a <condition> is satisfied for that <item>.

3. Ranges

A range is a sequence of consecutive integers, but it is not a list. More generally, range(a, b) returns a sequence that starts from a and includes every consecutive integer in order until b, but not including b.

We can turn a range into a list by calling a list constructor on it:

assert [-2, -1, 0, -1] == list(range(-2, 2))

4. Strings

A string is a sequence of characters. String literals can be single-quoted, double-quoted, or multi-line:

single = 'I am a string!'
double = "I've got an apostrophe"
hi = '您好'

# 'The Zen of Python\nclaims, Readability counts.\nRead more: import this.'
multi = """The Zen of Python
           claims, Readability counts.
           Read more: import this."""

We can use a backslash, \, to escape the following character, which allows Python to treat both it and the following character as one element. Escaping characters have several uses: for example, \n is a line feed character, which represents a new line.

5. Tuples

Tuples are an immutable sequence. You can define tuples with literals like so:

t = (3, 4, 5, 6)
l = tuple([3, 4, 5])          # (3, 4, 5)
single = (2,)
Last modified: 2025-10-03 13:47