4

I would like to get a tuple of n tuples but I don't know how to go about it.

From this ([1, 25, 30], 'a') I tried this ([1, 25, 30], 'a')*3 but it doesn't work.

Basically I wanna get feedback like this:

Out[29]: 
(([1, 25, 30], 'a'),
 ([1, 25, 30], 'a'),
 ([1, 25, 30], 'a'),
 ([1, 25, 30], 'a'),
 ([1, 25, 30], 'a'),
 ([1, 25, 30], 'a'),
 ([1, 25, 30], 'a'),
 ([1, 25, 30], 'a'))
Marc
  • 320
  • 2
  • 9

3 Answers3

3

You have to wrap the tuple into another one-elemented tuple before "multiplying":

>>> ([1, 25, 30], 'a') * 3
([1, 25, 30], 'a', [1, 25, 30], 'a', [1, 25, 30], 'a')
>>> (([1, 25, 30], 'a'),) * 3
(([1, 25, 30], 'a'), ([1, 25, 30], 'a'), ([1, 25, 30], 'a'))

But keep in mind, that this will create a tuple with 3 references to the same tuple. For a pure, unmodifyable tuple this would be fine, but yours has mutable parts, that, if modified, will be modified in all the "different" references.

>>> t = (([1, 25, 30], 'a'),) * 3
>>> t[0][0][1] = 42
>>> t
(([1, 42, 30], 'a'), ([1, 42, 30], 'a'), ([1, 42, 30], 'a'))

If you do not want this, better use tuple with a generator expression:

>>> t = tuple( ([1, 25, 30], 'a') for _ in range(3))
>>> t[0][0][1] = 42
>>> t
(([1, 42, 30], 'a'), ([1, 25, 30], 'a'), ([1, 25, 30], 'a'))
tobias_k
  • 81,265
  • 12
  • 120
  • 179
1

The outer parentheses are only grouping parentheses. You need to add a comma to make the outer enclosure a tuple:

t = (([1, 25, 30], 'a'),) * 3
print(t)

# Output
# (([1, 25, 30], 'a'), ([1, 25, 30], 'a'), ([1, 25, 30], 'a'))
mhhabib
  • 2,975
  • 1
  • 15
  • 29
1
import pprint
tt = (([1, 25, 30], 'a'),)*8
pprint.pprint(tt)

Output:

(([1, 25, 30], 'a'),
 ([1, 25, 30], 'a'),
 ([1, 25, 30], 'a'),
 ([1, 25, 30], 'a'),
 ([1, 25, 30], 'a'),
 ([1, 25, 30], 'a'),
 ([1, 25, 30], 'a'),
 ([1, 25, 30], 'a'))

But keep in mind that those will all be references to the same object!

tt[0][0][0] = 2 # this will change the first list item in all tuples!
pprint.pprint(tt)

Output:

(([2, 25, 30], 'a'),
 ([2, 25, 30], 'a'),
 ([2, 25, 30], 'a'),
 ([2, 25, 30], 'a'),
 ([2, 25, 30], 'a'),
 ([2, 25, 30], 'a'),
 ([2, 25, 30], 'a'),
 ([2, 25, 30], 'a'))

See: List of lists changes reflected across sublists unexpectedly

Mike Scotty
  • 10,530
  • 5
  • 38
  • 50