Python Sequences

Summary: in this tutorial, you’ll learn about the Python sequences and their basic operations.

Introduction to Python sequences #

A sequence is a positionally ordered collection of items. And you can refer to any item in the sequence by using its index number e.g., s[0] and s[1].

In Python, the sequence index starts at 0, not 1. So the first element is s[0] and the second element is s[1]. If the sequence s has n items, the last item is s[n-1].

Python has the following built-in sequence types: lists, bytearrays, strings, tuples, range, and bytes. Python classifies sequence types as mutable and immutable.

The mutable sequence types are lists and bytearrays while the immutable sequence types are strings, tuples, range, and bytes.

A sequence can be homogeneous or heterogeneous. In a homogeneous sequence, all elements have the same type. For example, strings are homogeneous sequences where each element is of the same type.

Lists, however, are heterogeneous sequences where you can store elements of different types including integer, strings, objects, etc.

In general, homogeneous sequence types are more efficient than heterogeneous in terms of storage and operations.

Sequence type vs iterable type #

An iterable is a collection of objects where you can get each element one by one. Therefore, any sequence is iterable. For example, a list is iterable.

However, an iterable may not be a sequence type. For example, a set is iterable but it’s not a sequence.

Generally speaking, iterables are more general than sequence types.

Standard Python sequence methods #

The following explains some standard sequence methods:

Counting elements of a Python sequence #

To get the number of elements of a sequence, you use the built-in len function:

len(seq)

The following example uses the len function to get the number of items in the cities list:

cities = ['San Francisco', 'New York', 'Washington DC']

print(len(cities))
Code language: PHP (php)

Try it

Output:

3

Checking if an item exists in a Python sequence #

To check if an item exists in a sequence, you use the in operator:

element in seq

The following example uses the in operator to check if the 'New York' is in the cities list:

cities = ['San Francisco', 'New York', 'Washington DC']
print('New York' in cities)Code language: PHP (php)

Try it

Output:

TrueCode language: PHP (php)

To negate the in operator, you use the not operator. The following example checks if 'New York' is not in the cities list:

cities = ['San Francisco', 'New York', 'Washington DC']
print('New York' not in cities)Code language: PHP (php)

Try it

Output:

FalseCode language: PHP (php)

Finding the index of an item in a Python sequence #

The seq.index(e) returns the index of the first occurrence of the item e in the sequence seq:

seq.index(e)Code language: CSS (css)

For example:

numbers = [1, 4, 5, 3, 5, 7, 8, 5]

print(numbers.index(5))
Code language: PHP (php)

Try it

Output:

2