Files
2024-05-06 21:19:10 -06:00

2.3 KiB

Certainly! In Python, array sequences are data structures that store a collection of elements in a specific order. The three main built-in array sequence types in Python are lists, tuples, and strings. Let's explore each of them:

  1. Lists (square brackets []):

    • Lists are mutable, meaning you can modify, add, or remove elements after creation.
    • Elements in a list can be of different data types (e.g., integers, strings, objects).
    • Lists are defined using square brackets [] and elements are separated by commas.
    • Example:
      my_list = [1, 2, 3, "apple", True]
      
  2. Tuples (parentheses ()):

    • Tuples are immutable, meaning you cannot modify them once they are created.
    • Elements in a tuple can be of different data types, similar to lists.
    • Tuples are defined using parentheses () and elements are separated by commas.
    • Example:
      my_tuple = (1, 2, 3, "apple", True)
      
  3. Strings (double quotes ""):

    • Strings are immutable sequences of characters.
    • They are defined using either single quotes '' or double quotes "".
    • Example:
      my_string = "Hello, World!"
      

Indexing: All three array sequence types support indexing, which allows you to access individual elements within the sequence using their position or index. In Python, indexing starts from 0.

Example:

my_list = [1, 2, 3, 4, 5]
print(my_list[0])  # Output: 1
print(my_list[2])  # Output: 3

my_tuple = (1, 2, 3, 4, 5)
print(my_tuple[1])  # Output: 2
print(my_tuple[4])  # Output: 5

my_string = "Hello"
print(my_string[0])  # Output: 'H'
print(my_string[4])  # Output: 'o'

You can also use negative indexing to access elements from the end of the sequence. For example, -1 refers to the last element, -2 refers to the second-to-last element, and so on.

Example:

my_list = [1, 2, 3, 4, 5]
print(my_list[-1])  # Output: 5
print(my_list[-3])  # Output: 3

In addition to indexing, array sequences in Python support various operations like slicing (extracting a portion of the sequence), concatenation (joining sequences together), and more.

I hope this helps you understand array sequences, lists, tuples, strings, and indexing in Python better! Let me know if you have any further questions.