Curriculum
In Python, a sequence is an ordered collection of elements, where each element is identified by an index. There are several built-in sequence types in Python, each with its own set of properties and methods. The three main sequence types are lists, tuples, and strings.
Lists are the most versatile of the sequence types, and are used to store a collection of mutable items. Lists can be modified in place, and can contain items of any type.
# Create a list of integers numbers = [1, 2, 3, 4, 5] # Add an item to the end of the list numbers.append(6) # Remove an item from the list numbers.remove(3) # Iterate over the list for n in numbers: print(n)
Tuples are similar to lists, but are immutable (cannot be modified in place). Tuples are commonly used to group related values together, and are often returned by functions as a way of returning multiple values.
# Create a tuple of strings person = ('Alice', 'Smith', 25, 'female') # Get the first item in the tuple first_name = person[0] # Iterate over the tuple for item in person: print(item)
Strings are a sequence of characters, and are immutable like tuples. Strings can be concatenated and sliced like lists and tuples, but cannot be modified in place.
# Create a string message = "Hello, world!" # Get the length of the string length = len(message) # Get a substring of the string substring = message[7:12] # Iterate over the string for character in message: print(character)
In addition to these built-in sequence types, there are several other sequence-like types in Python, such as byte arrays and range objects. By understanding the properties and methods of each sequence type, you can choose the appropriate data structure for your particular use case and optimize your code for efficiency and readability.