Reputation: 5021
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.
Upvotes: 17
Views: 28562
Reputation: 52489
This is just a minor change to the main answer. I just needed to see this a little more concretely for my case, is all.
N
None
sFor anyone just trying to get a tuple of N elements of None
, or some other simple value, to initialize some tuple variables, it would look like this:
N = 3
# Create `(None, None, None)`
tuple_of_nones = (None,) * N
# Create `(3, 3, 3, 3, 3)`
tuple_of_five_threes = (3,) * 5
# etc.
Example run and output in an interpreter:
>>> N = 3
>>> tuple_of_nones = (None,) * N
>>> tuple_of_nones
(None, None, None)
>>> tuple_of_five_threes = (3,) * 5
>>> tuple_of_five_threes
(3, 3, 3, 3, 3)
Upvotes: 1
Reputation: 78546
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']]
Upvotes: 34