
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
How does repetition operator work on list in Python?
We are accustomed to using the * symbol to represent multiplication, but when the operand on the left side of the * is a list, it becomes the repetition operator. The repetition operator makes multiple copies of a list and joins them all together. Lists can be created using the repetition operator, *. For example,
Example
numbers = [0] * 5 print numbers
Output
This will give the output −
[0, 0, 0, 0, 0]
[0] is a list with one element, 0. The repetition operator makes 5 copies of this list and joins them all together into a single list. Another example using multiple elements in the list.
Example
numbers = [0, 1, 2] * 3 print numbers
Output
This will give the output −
[0, 1, 2, 0, 1, 2, 0, 1, 2]
Note that Python creates shallow copies of the lists in this. So changing objects at one place will change them at all places they are repeated. If you don't want this behaviour, don't use repetition operator to create lists.
- Related Articles
- How does the repetition operator work on a tuple in Python?
- How does * operator work on list in Python?
- How does in operator work on list in Python?
- How does concatenation operator work on list in Python?
- How does concatenation operator work on tuple in Python?
- How does the * operator work on a tuple in Python?
- How does the del operator work on a tuple in Python?
- How does the 'in' operator work on a tuple in Python?
- Element repetition in list in Python
- JavaScript : Why does % operator work on strings? - (Type Coercion)
- Python – Index Value repetition in List
- How does the Comma Operator work in C++
- How does a list work in Java?
- How does comparison operator work with date values in MySQL?
- How does == operator works in Python 3?
