Table of Contents

What Will You Learn
You’ll learn how to access, slice, modify, and loop through sequences, understand their differences, and choose the right type for your tasks. With clear examples, this guide helps you master essential operations like indexing, concatenation, repetition, and immutability handling.


Working with sequences is the foundation of most operations in any programming language. Regardless of the task — text analysis, storing a set of values, managing product lists or parameters — structures that can be called sequences are used everywhere. They allow accessing data by index, iterating over elements, modifying contents, and creating new representations of information.

In programming languages, sequences are considered a fundamental category of data types. These include familiar elements such as strings, lists, and tuples. These structures share the characteristic of storing ordered sets of values, with the ability to manage them programmatically: modify, copy, combine, and filter.

If you’re just starting to learn programming, sequences are one of those topics that appear in virtually every project. Understanding the differences between types and their behaviors is the foundation of confident and professional development.

What are the Sequence Data Types in Python?

Sequences are data types that store elements in a specific order. Each element in such a structure has an index starting from zero and can be accessed by that index. All sequences in the programming language support basic operations: getting the length (len()), iterating in a loop (for), slicing ([start:stop]), checking for membership (in), concatenation (+), and repetition (*).

Built-in sequences include:

  • str — a string of characters;
  • list — a mutable list of values;
  • tuple — an immutable tuple.

Other sequences include range, bytearray, bytes, but this article focuses on the basic and most commonly used structures: strings, lists, and tuples.

Sequences are not just a way to store data. They are a universal interface for working with collections where order and index-based access are important. Thanks to these types, the language remains concise and expressive even for complex tasks.

What are characteristics of Python Sequences?

All sequences have a set of common characteristics that make working with them predictable and universal. This allows applying the same approaches to different types without duplicating logic.

Main characteristics of sequences:

  • Ordered. Each element has a fixed position. Order matters: [1, 2, 3] is not the same as [3, 2, 1].
  • Indexable. You can access an element by its position number: s[0], s[-1].
  • Iterable. Sequences can be iterated in a for loop or converted to a list: for item in sequence.
  • Slicable. Any sequence can be sliced using [:], for example s[1:4].
  • in / not in operations. You can check if an element is in a sequence: 'a' in 'apple', 2 in [1, 2, 3].
  • Support for len() function. All sequences return the number of elements using len().
  • Support for concatenation and repetition. Operators + and * work for combining and duplicating content.
  • Nested support. Sequences can contain other sequences, including themselves.

Understanding these characteristics simplifies learning specific types and makes your code more versatile and logical.

Python String

A string (str) is an ordered sequence of characters. It is used to store text: words, sentences, numbers in textual form, names, addresses, and other textual data. Strings are enclosed in single ('...') or double ("...") quotes. Both options are equivalent.

 
    text = "Hello, world!"
    name = 'Alice'

In this example, text is a string containing the phrase "Hello, world!", and name is a string with the name "Alice". Strings can be created using triple quotes ('''...''' or """...""") for multi-line text. This is useful for long texts, documentation, or comments.

Strings are immutable — once created, individual characters cannot be changed. All operations like replacing a character or removing a space create a new string.

Basic string operations:

  • Access by index: text[0]'H'
  • String length: len(text)13
  • Slicing: text[0:5]'Hello'
  • Repetition: 'Hi ' * 3'Hi Hi Hi '
  • Membership check: 'world' in textTrue

Strings include dozens of built-in methods: lower(), upper(), replace(), split(), strip(), allowing for professional text processing.

Python List

A list (list) is a mutable sequence of any values. It can contain numbers, strings, other lists, or even a mix of different types. Lists are one of the most flexible and frequently used tools.

 
    numbers = [1, 2, 3, 4]
    mixed = ["Alice", 30, True, [1, 2]]

In this example, numbers is a list of integers, while mixed contains a string, an integer, a boolean, and another list. Lists are created using square brackets ([...]) and can be empty or contain any number of elements.

Lists are ordered: the order of elements is preserved. You can access them by index, slice them, and iterate over them. Lists can also contain duplicates.

Lists are mutable: you can add, remove, and replace elements without creating a new list. This makes them ideal for storing dynamic data.

Useful list operations:

  • Adding an element: numbers.append(5)
  • Removing an element: numbers.remove(2)
  • Modification: numbers[0] = 100
  • List length: len(numbers)4
  • Slicing: numbers[1:3][2, 3]
  • Looping:
 
    for num in numbers: 
      print(num)

In this example, the loop iterates over each element in the list and prints it. Lists are versatile and can be used for a wide range of tasks, from simple data storage to complex data manipulation.

The list is a structure you’ll use in nearly every project: from storing form values to processing files and API responses.

Python Tuple

A tuple (tuple) is an immutable sequence. It is similar to a list but does not allow changes to its contents once created. Tuples are created using commas and parentheses:

 
    coordinates = (10, 20)
    person = ("Alice", 30)

In this example, coordinates is a tuple of two integers, and person is a tuple containing a string and an integer. Tuples are often used to group related data together.

Tuples are useful when you need to lock in a set of values. For example, map coordinates, RGB color, or connection parameters. They can’t be accidentally modified — which increases code reliability.

Available operations:

  • Indexing: coordinates[0]10
  • Slicing: person[0:2]("Alice", 30)
  • Iteration:
 
    for item in person:
      print(item)

In this example, the loop iterates over each element in the tuple and prints it. Tuples are often used for fixed collections of items, such as coordinates or RGB values.

Tuples are also used as keys in dictionaries — unlike lists, they are hashable and considered safe to use as immutable identifiers.

Immutable and Mutable Sequences

In programming languages, all sequences fall into two key categories: mutable and immutable. This is a fundamental distinction that affects variable behavior, functions, and data structure design overall.

A mutable object is one whose content can be changed without creating a new object. An immutable one cannot be changed: any operation creates a new instance in memory.

For a beginner programmer, it’s important to understand that not all collections behave the same: a list and a string may look similar (both support indexing, slicing, iteration), but one is changeable, and the other is not.

Key Differences Between Immutable and Mutable Sequences

Mutable sequences allow you to directly modify their contents without creating a new object. This is convenient, but requires caution when passing such structures to functions, where they might be unintentionally changed.

Immutable sequences are reliable: their contents are fixed after creation. They are considered safe for repeated use and are suitable for storing constant data.

  • Mutable structures can be modified "in place", while immutable ones must be replaced entirely.
  • Immutable objects are safe to use as dictionary keys or set elements.
  • All operations on immutable types return a new object, leaving the original unchanged.
  • Mutable types require attention when copying — simple assignment is not considered a true copy.
  • Immutable sequences provide predictability, especially in functions.
  • Immutable types have lower overhead for data protection and are processed faster in memory.
  • Mutable objects are convenient for building dynamic structures, such as product lists, task queues, or data buffers.

Comparison of Mutable and Immutable Sequences

Data Type Mutability Example Note
str ❌ No "hello" Any modification creates a new string
list ✅ Yes [1, 2, 3] You can add, remove, and change elements
tuple ❌ No (1, 2, 3) Contents are fixed
range ❌ No range(5) Acts as an immutable generator
bytes ❌ No b"abc" Byte sequence, immutable
bytearray ✅ Yes bytearray(b"abc") You can edit individual bytes
memoryview ✅ Yes memoryview(b"abc") Access to memory without copying

Why this matters:

  • Safety. Immutable objects are safe when passed between functions — no one can accidentally change their contents.
  • Performance. These objects are processed faster and take up less memory.
  • Compatibility. Only immutable objects can be used as dictionary keys or set elements.

For beginners, it’s important to remember a simple rule: if a structure can be changed — it's potentially risky when passed to a function and requires caution. Immutable ones are more predictable and convenient when designing logic where values must remain fixed.

Beginner Mistakes

Sequences are a convenient and versatile tool, but their apparent simplicity often leads beginners to make serious logical and syntactical errors. Below is a list of common problems and how to solve them.

1. Attempting to Modify a String

Error:

 
    text = "hello"
    text[0] = "H"# TypeError

Reason:
A string is an immutable type. You can't directly change a character by index.

Solution: Create a new string based on the existing one:

text = "H" + text[1:]

2. List Copying Error

Error:

 
    a = [1, 2, 3]
    b = a b.append(4)
    print(a) # [1, 2, 3, 4] — unexpected result

Reason:
a and b refer to the same object. Changes to one affect the other.

Solution: Use copying:

b = a.copy()

3. Index Out of Range

Error:

 
    items = [10, 20, 30]
    print(items[5]) # IndexError
  

Reason:
Accessing a non-existent index goes beyond the list or string boundaries.

Solution: Check the length before accessing:

 
    if index < len(items): 
      print(items[index])
  

4. Using a Mutable Object Inside a tuple

Error:

 
    data = ([1, 2], "fixed") 
    data[0][0] = 100# tuple contains a mutable list
  

Reason:
Although the tuple itself is immutable, it can contain mutable objects. This breaks the expected "frozen" behavior.

Solution: Avoid nested mutable structures inside a tuple if complete immutability is expected.

5. Mistakes Using += with Tuples

Error:

 
    t = (1, 2)
    t += (3,)
    print(t) # Works, but creates a new object
  

Reason:
A tuple is immutable. The += operator creates a new object, which may be misleading.

Solution: Understand that any "change" to a tuple means creating a new copy:

t = t + (4,)

6. Incorrect Use of in in Multidimensional Lists

Error:

 
    matrix = [[1, 2], [3, 4]] 
    print(2 in matrix) # False
  

Reason:
The in operator checks the top-level only. 2 is inside a nested list, not at the top level.

Solution: Use a nested loop or any():

 found = any(2 in row for row in matrix)

Understanding these errors is an important step toward writing stable and predictable code. Sequences offer flexibility, but require attention to detail — especially with indexes, copies, and mutability.

Frequently Asked Questions

Which of the following built-in data types in Python are specifically sequence types?

The built-in sequence types in Python include:

  • str — string of characters;
  • list — list of values;
  • tuple — immutable collection;
  • range — generator of a sequence of integers;
  • bytes — immutable sequence of bytes;
  • bytearray — mutable version of bytes;
  • memoryview — access to a buffer as a sequence.

These types share a common interface: they support indexing, slicing, looping, in operations, the len() function, and concatenation (+, *). They are considered sequences because their contents are ordered and each element can be accessed by index.

What is the difference between a list and a tuple?

The key difference is mutability. A list is a mutable type, while a tuple is immutable.

  • list allows adding, removing, and changing elements:
 
        l = [1, 2, 3]
        l.append(4)
        l[0] = 100
      
  • tuple is fixed: its contents cannot be changed after creation:
 
      t = (1, 2, 3)
      # t[0] = 100 → TypeError
    

Tuples are used when immutability, structural reliability, or the ability to use a sequence as a dictionary key is important. Lists are used when the structure is dynamic and needs to change during program execution.

Can sequences contain elements of different data types?

Yes. Sequences in Python are heterogeneous, meaning they can contain values of different types:

mixed = [1, "two", True, 3.5]

This is especially convenient in development, as it allows combining different data types in one structure. However, it's important to remember: just because you can doesn’t mean you always should. It's better to maintain consistency unless heterogeneity is necessary.

How to copy a sequence safely in Python?

To copy a sequence, simply assigning it to another variable is not enough, as it will only create a new reference to the same object. To create a true copy, use:

  • For lists:
new_list = old_list.copy()

or

 new_list = old_list[:] 


  • For strings and tuples (since they are immutable): assignment is fine, but any changes will require creating a new object.

If the list contains nested lists, use copy.deepcopy() to fully copy all levels.

Is a string a sequence type in Python?

Yes. str is a fully-fledged sequence type. It supports indexing, slicing, iteration, in, +, * operations, and the len() function. Even though a string is made of characters, it can be manipulated similarly to a list:

 
      text = "hello"
      print(text[1:4])  # "ell"
      for char in text:
          print(char)
        

But a string is immutable, just like a tuple. Any operation that modifies a string actually creates a new object.