Sobes.tech
Intern
212

What is a sequence in Python?

Answer from AI

sobes.tech AI

A sequence in Python is an iterable object that orders elements according to certain rules. Each element within a sequence has an index starting from 0. The main types of built-in sequences include:

  • list: A mutable sequence.
  • tuple: An immutable sequence.
  • range: An immutable sequence of numbers generated "on the fly".
  • str: An immutable sequence of characters.
  • bytes: An immutable sequence of bytes.
  • bytearray: A mutable sequence of bytes.

Common characteristics of sequences:

  • Orderliness: Elements have a defined order and are accessible by index.
  • Indexing: Access to individual elements by their position (index). Both positive and negative indexing are supported.
  • Slicing: Ability to obtain a subsequence.
  • Iteration: You can iterate over a sequence (for example, using a for loop).
  • Operations: Common operations such as concatenation (+), repetition (*), and membership testing (in) are supported.
# Usage examples
my_list = [1, 2, 3, 4]
print(my_list[0]) # Indexing
print(my_list[1:3]) # Slicing

my_tuple = (5, 6, 7)
print(len(my_tuple)) # Length

my_string = "hello"
print('e' in my_string) # Membership check