Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create tuple of multiple items n Times in Python

Tags:

python

tuples

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.

like image 591
muazfaiz Avatar asked Nov 12 '16 23:11

muazfaiz


People also ask

How do you create a tuple with repetition of string n times in Python?

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.

Can a tuple have repeats?

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.


1 Answers

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']]
like image 108
Moses Koledoye Avatar answered Sep 24 '22 04:09

Moses Koledoye