Skip to main content

Command Palette

Search for a command to run...

Sequences in Python

Python Sequences: An Overview

Published
7 min read
Sequences in Python

In this comprehensive article, we will delve into the fascinating world of sequences in Python, exploring their intricacies and various applications. By providing a thorough examination of the different types of sequences available in Python, we aim to equip you with the knowledge and understanding necessary to effectively utilize them in your programming endeavors.

Sequences in Python are ordered collections of items. They are a fundamental concept in Python and are used extensively in programming to store and manipulate data. Python provides several built-in sequence types, each with its own characteristics and use cases.

Built-In Sequence Types

Mutable

  • lists

  • bytearrays

Immutable

  • strings

  • tuples (a tuple is more than just a sequence type)

  • range (more limited than lists, strings and tuples)

  • bytes

Additional Standard Types:

  • namedtuple

  • deque

  • array

Homogeneous sequences

Homogeneous sequences in Python are sequences where all elements are of the same data type. This means that every element in the sequence is expected to be of a consistent data type, such as integers, floats, strings, or any other data type. Homogeneous sequences are commonly used in scenarios where you want to work with a collection of data of a specific type. The most common homogeneous sequences in Python are lists and arrays from external libraries like NumPy.

Here's an example using a homogeneous list in Python:

# Homogeneous list of integers
int_list = [1, 2, 3, 4, 5]

# Homogeneous list of strings
str_list = ["apple", "banana", "cherry", "date"]

# Homogeneous list of floats
float_list = [1.0, 2.5, 3.14, 4.7, 5.2]

Heterogeneous sequences

Heterogeneous sequences in Python are sequences where elements can be of different data types. In other words, in a heterogeneous sequence, you can have a mix of integers, floats, strings, or any other data type within the same sequence. Python's built-in list is a common example of a heterogeneous sequence, as it can hold elements of various types.

Here's an example of a heterogeneous list:

heterogeneous_list = [1, 2.5, "Hello", True]

In this list, you have an integer (1), a floating-point number (2.5), a string ("Hello"), and a boolean value (True) all coexisting within the same sequence.

Iterable Type vs. Sequence Type

"Iterable type" and "sequence type" are related but distinct concepts in Python. Both pertain to the ability to work with collections of data, but they have different characteristics and use cases.

Iterable Type:

  • An iterable is an object in Python that can be looped over or iterated upon.

  • It defines an __iter__() method, which returns an iterator. The iterator is responsible for producing values one at a time during iteration.

  • Iterables do not guarantee the presence of a specific order or indexing, and they may or may not have a finite number of elements.

  • Iterables are more general and encompass various types of collections, not just sequences.

Common examples of iterables include lists, sets, dictionaries (when you iterate over keys or values), and custom objects that implement the iterable protocol.

my_list = [1, 2, 3, 4, 5]
my_set = {10, 20, 30}
my_dict = {"a": 1, "b": 2}

for item in my_list:
    print(item)

for value in my_set:
    print(value)

for key in my_dict:
    print(key, my_dict[key])

Sequence Type:

  • A sequence is a specific kind of iterable that represents an ordered collection of elements.

  • Sequences are characterized by having a well-defined order, and each element is associated with an index.

  • Elements in a sequence can be accessed by their position (index) within the sequence.

  • Common examples of sequence types in Python include lists, tuples, and strings.

my_list = [1, 2, 3, 4, 5]
my_tuple = (10, 20, 30)
my_string = "Hello, Python"

print(my_list[2])     # Accessing an element by index in a list
print(my_tuple[1])    # Accessing an element by index in a tuple
print(my_string[6])   # Accessing a character by index in a string

In summary, the key difference is that "iterable" is a more general concept that includes any object that can be looped over, whereas "sequence" is a specific type of iterable with a well-defined order and indexing. Sequences are a subset of iterables, and they have additional properties related to their ordered nature, making them suitable for tasks where element order matters, such as indexing and slicing.

Standard Sequence Methods

Built-in sequence types, both mutable and immutable, support the following methods

in

In Python, the expression x in s is a membership test that checks whether the element x is present in the sequence or collection s. It returns a Boolean value, True if x is found in s, and False otherwise.

my_list = [1, 2, 3, 4, 5]
is_present = 3 in my_list  # True

not in

In Python, the expression x not in s is a membership test that checks whether the element x is not present in the sequence or collection s. It returns a Boolean value: True if x is not found in s, and False if x is found in s.

my_list = [1, 2, 3, 4, 5]
is_not_present = 6 not in my_list  # True

len(s)

This expression returns the length of the sequence s. The length is the number of elements in the sequence. This is a common operation to find out how many items are in a sequence.

my_list = [1, 2, 3, 4, 5]
length = len(my_list)  # Returns 5

min(s)

This expression returns the minimum element from the sequence s. It is used to find the smallest value in a sequence of comparable elements, such as numbers or strings.

my_list = [10, 5, 15, 20, 2]
minimum = min(my_list)  # Returns 2

max(s)

The max(s) expression is used with sequences in Python to find the maximum (largest) element in the sequence s. It returns the highest value in the sequence, and it's commonly used to find the maximum value in a sequence of comparable elements, such as numbers or strings.

my_list = [10, 5, 15, 20, 2]
maximum = max(my_list)  # Returns 20

index

s.index(x)

The s.index(x) expression is used with sequences in Python to find the index (position) of the first occurrence of the element x in the sequence s. It returns the index of x if x is found in s. If x is not found in s, it raises a ValueError exception.

Here's how to use s.index(x):

my_list = [10, 20, 30, 40, 50]
index = my_list.index(30)  # Returns 2

s.index(x, i)

The s.index(x, i) expression is used with sequences in Python to find the index (position) of the first occurrence of the element x in the sequence s, starting the search from index i. It returns the index of x if x is found in s after or at position i. If x is not found in the specified portion of s, it raises a ValueError exception.

Here's how to use s.index(x, i):

my_list = [10, 20, 30, 20, 40]
index = my_list.index(20, 2)  # Returns 3

s.index(x, i, j)

The s.index(x, i, j) expression is used with sequences in Python to find the index (position) of the first occurrence of the element x in the specified slice of the sequence s, starting from index i (inclusive) and ending at index j (exclusive). It returns the index of x if x is found within the specified slice of s. If x is not found in the specified slice, it raises a ValueError exception.

Here's how to use s.index(x, i, j):

my_list = [10, 20, 30, 20, 40]
index = my_list.index(20, 1, 4)  # Returns 1

Slicing

Slicing in Python lists allows you to extract a portion of a list by specifying a range of indices. You can create a new list containing the selected elements. The basic syntax for slicing a list is my_list[start:stop], where start is the index of the first element you want to include, and stop is the index of the first element you want to exclude.

# Slice from index 2 (inclusive) to index 5 (exclusive)
sub_list = my_list[2:5]  # Result: [2, 3, 4]

# Slice from the beginning to index 3 (exclusive)
sub_list = my_list[:3]  # Result: [0, 1, 2]

# Slice from index 5 (inclusive) to the end
sub_list = my_list[5:]  # Result: [5, 6, 7, 8, 9]

In conclusion, sequences are an essential aspect of Python programming, providing a means to store and manipulate ordered collections of data. With a variety of built-in sequence types, both mutable and immutable, Python offers versatile options to handle a wide range of applications. Understanding the differences between iterable and sequence types, and mastering sequence methods and slicing, empowers you to effectively utilize sequences in your programming projects.

Python

Part 21 of 30

The Python Learning Series is a comprehensive and structured approach to mastering the Python programming. It is designed to cater to learners of all levels,from beginners to experienced.

Up next

Lists in Python

Understanding Python Lists