Sequence Basics in Python
What is a Sequence?
In Python, a sequence is an ordered collection of elements that can be indexed and iterated. Python provides several built-in sequence types that are fundamental to understanding sequence manipulation:
Sequence Type |
Characteristics |
Mutability |
List |
Ordered, allows duplicates |
Mutable |
Tuple |
Ordered, allows duplicates |
Immutable |
String |
Ordered sequence of characters |
Immutable |
Types of Sequences
Lists
Lists are the most versatile sequence type in Python. They can contain elements of different types and are defined using square brackets.
## Creating a list
numbers = [1, 2, 3, 4, 5]
mixed_list = [1, "hello", 3.14, True]
## List operations
numbers.append(6) ## Add an element
numbers.extend([7, 8]) ## Add multiple elements
Tuples
Tuples are immutable sequences, typically used for grouped, unchangeable data.
## Creating a tuple
coordinates = (10, 20)
person = ("John", 30, "Engineer")
Strings
Strings are sequences of characters, immutable and indexed.
## String as a sequence
text = "Python"
print(text[0]) ## Prints 'P'
print(text[1:4]) ## Prints 'yth'
Sequence Flow Visualization
graph TD
A[Sequence Types] --> B[Lists]
A --> C[Tuples]
A --> D[Strings]
B --> E[Mutable]
C --> F[Immutable]
D --> F
Key Sequence Operations
- Indexing
- Slicing
- Concatenation
- Repetition
- Length checking
## Sequence operations example
sequence = [1, 2, 3, 4, 5]
print(len(sequence)) ## Length: 5
print(sequence[2]) ## Indexing: 3
print(sequence[1:4]) ## Slicing: [2, 3, 4]
When working with sequences in LabEx Python environments, consider:
- Lists are dynamic but slower for large datasets
- Tuples are faster and memory-efficient
- Use appropriate sequence type based on your specific use case
Common Use Cases
- Data storage
- Iteration
- Function return values
- Algorithm implementations
By understanding these sequence basics, you'll be well-prepared to explore more advanced sequence manipulation techniques in Python.