Sobes.tech
Junior

What are the sequences in Python?

sobes.tech AI

Answer from AI

In Python, the following built-in sequence types exist:

  1. Immutable sequences:

    • Strings (str): Sequences of characters.
    • Tuples (tuple): Ordered collections of elements that cannot be changed after creation.
    • Byte sequences (bytes): Sequences of bytes (immutable counterpart of bytearray).
  2. Mutable sequences:

    • Lists (list): Ordered collections of elements that can be modified.
    • Byte arrays (bytearray): Mutable sequences of bytes.

Main operations common to all sequence types include:

  • Index access: sequence[index]
  • Slicing: sequence[start:end:step]
  • Length: len(sequence)
  • Membership check: element in sequence
  • Concatenation: sequence1 + sequence2 (creates a new object for mutable sequences)
  • Repetition: sequence * number (creates a new object for mutable sequences)

Operations specific to mutable sequences include:

  • Changing an element by index: sequence[index] = new_value
  • Changing a slice: sequence[start:end] = new_sequence
  • Adding elements: sequence.append(element), sequence.extend(sequence)
  • Inserting elements: sequence.insert(index, element)
  • Removing elements: del sequence[index], sequence.remove(element), sequence.pop(index)

Examples of usage:

# String (immutable)
my_string = "Hello"
# Tuple (immutable)
my_tuple = (1, 2, 3)
# List (mutable)
my_list = [4, 5, 6]
# Bytes (immutable)
my_bytes = b'world'
# Byte array (mutable)
my_bytearray = bytearray(b'python')

# Index access
print(my_string[0])  # Output: H
print(my_tuple[1])   # Output: 2
print(my_list[2])    # Output: 6

# Slicing
print(my_string[1:4]) # Output: ell
print(my_list[:2])    # Output: [4, 5]

# Modifying list (immutable types do not support this operation)
my_list[0] = 10
print(my_list) # Output: [10, 5, 6]

# Concatenation
new_list = my_list + [7, 8]
print(new_list) # Output: [10, 5, 6, 7, 8]

# Adding to list
my_list.append(9)
print(my_list) # Output: [10, 5, 6, 9]