A list can be created n times:
a = [['x', 'y']]*3 # Output = [['x', 'y'], ['x', 'y'], ['x', 'y']]
But I want to make a tuple in such a way but it not returning the similar result as in the list. I am doing the following:
a = (('x','y'))*4 # Output = ('x', 'y', 'x', 'y', 'x', 'y', 'x', 'y')
Expected_output = (('x', 'y'), ('x', 'y'), ('x', 'y'), ('x', 'y'))
Any suggestions ? Thanks.
To repeat a tuple in Python, We use the asterisk operator ” * ” The asterisk. is used to repeat a tuple n (number) of times. Which is given by the integer value ” n ” and creates a new tuple value. It uses two parameters for an operation: the integer value and the other is a tuple.
The * symbol is commonly used to indicate multiplication, however, it becomes the repetition operator when the operand on the left side of the * is a tuple. The repetition operator duplicates a tuple and links all of them together.
The outer parentheses are only grouping parentheses. You need to add a comma to make the outer enclosure a tuple:
a = (('x','y'),)*4
print(a)
# (('x', 'y'), ('x', 'y'), ('x', 'y'), ('x', 'y'))
For context, it wouldn't make sense to get a tuple while doing f = (x + y)
, for example.
In order to define a singleton tuple, a comma is usually required:
a = (5) # integer
a = (5,) # tuple
a = 5, # tuple, parens are not compulsory
On a side note, duplicating items across nested containers would require more than just a simple mult. operation. Consider your first operation for example:
>>> a = [['x', 'y']]*3
>>> # modify first item
...
>>> a[0][0] = 'n'
>>> a
[['n', 'y'], ['n', 'y'], ['n', 'y']]
There is essentially no first item - the parent list contains just one list object duplicated across different indices. This might not be particularly worrisome for tuples as they are immutable any way.
Consider using the more correct recipe:
>>> a = [['x', 'y'] for _ in range(3)]
>>> a[0][0] = 'n'
>>> a
[['n', 'y'], ['x', 'y'], ['x', 'y']]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With