Create tuple of multiple items n Times in Python
Asked Answered
F

2

17

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.

Fission answered 12/11, 2016 at 23:16 Comment(0)
G
33

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']]
Goodish answered 12/11, 2016 at 23:19 Comment(4)
Thanks. But whats is the reason for this small difference ?Fission
This is to differentiate between closed braces used as a bracket (for example (5) => 5) and to represent a tuple.Mattiematting
Do note that the final result is a tuple containing four references to the same tuple (id(a[0]) == id(a[1]) evaluates to True). Tuples are immutable, so it doesn't matter, but if you had four of the same list inside your tuple and modified one, the results could be surprising.Omnidirectional
@StevenRumbalski I'll add that as a comment regarding the list part particularly. Good you notedGoodish
C
0

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.

Tuple of N Nones

For 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)
Confect answered 7/8, 2023 at 21:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.