How does the repetition operator work on a tuple in Python?

PythonServer Side ProgrammingProgramming

We are accustomed to using the * symbol to represent multiplication, but when the operand on the left side of the * is a tuple, it becomes the repetition operator. The repetition operator makes multiple copies of a tuple and joins them all together. Tuples can be created using the repetition operator, *. 

example

numbers = (0,) * 5  # we use the comma to denote that this is a single valued tuple and not an #expression
print numbers

Output

This will give the output −

(0, 0, 0, 0, 0)

[0] is a tuple with one element, 0.  The repetition operator makes 5 copies of this tuple and joins them all together into a single tuple. Another example using multiple elements in the tuple.

Example

numbers = (0, 1, 2) * 3
print numbers

Output

This will give the output −

(0, 1, 2, 0, 1, 2, 0, 1, 2)
raja
Published on 05-Jan-2018 17:25:25
Advertisements