Repetition Methods
Multiplication Operator for Sequence Repetition
Python provides a simple and intuitive way to repeat sequence elements using the *
operator:
## List repetition
numbers = [1, 2, 3] * 3
print(numbers) ## Output: [1, 2, 3, 1, 2, 3, 1, 2, 3]
## String repetition
word = "Hello " * 2
print(word) ## Output: Hello Hello
## Tuple repetition
repeated_tuple = (1, 2) * 4
print(repeated_tuple) ## Output: (1, 2, 1, 2, 1, 2, 1, 2)
Repetition Methods Comparison
Method |
Sequence Type |
Syntax |
Example |
Multiplication |
List, Tuple, String |
sequence * n |
[1,2] * 3 |
List Comprehension |
List |
[x for _ in range(n)] |
[1 for _ in range(3)] |
Itertools Repeat |
Any Iterable |
itertools.repeat(x, n) |
list(itertools.repeat(1, 3)) |
Advanced Repetition Techniques
List Comprehension
## Repeat complex elements
complex_list = [[0] * 3 for _ in range(4)]
print(complex_list)
## Output: [[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]]
import itertools
## Using itertools for repetition
repeated_items = list(itertools.repeat('a', 3))
print(repeated_items) ## Output: ['a', 'a', 'a']
Repetition Flow
graph TD
A[Repetition Method] --> B{Sequence Type}
B --> |List| C[Multiplication Operator]
B --> |String| C
B --> |Tuple| C
B --> |Complex Repetition| D[List Comprehension]
B --> |Flexible Repetition| E[Itertools]
- Multiplication operator (
*
) is most efficient for simple repetitions
- List comprehension offers more flexibility
- Itertools provides advanced repetition capabilities
LabEx Insight
LabEx recommends understanding these methods to choose the most appropriate repetition technique for your specific use case.
Common Pitfalls
## Careful with mutable objects
nested = [[]] * 3
nested[0].append(1)
print(nested) ## Unexpected result: [[1], [1], [1]]
## Safer approach
nested = [[] for _ in range(3)]
nested[0].append(1)
print(nested) ## Correct: [[1], [], []]