2

I need to create a nested tuple in which some values are the same, so I tried multiplying them.

t = ((('a', 'b'),) * 3)
print t

Prints

(('a', 'b'), ('a', 'b'), ('a', 'b'))

Is there a syntactically nicer way to do this?

Thanks.

2
  • 1
    Why the outer parentheses? They're not doing anything; they're just grouping parentheses, like in (1 + 2) * 3, but in a context where they don't help disambiguate any grouping. Commented Aug 4, 2014 at 8:23
  • My thinking was that they were necessary to create the outer tuple, rather than for any grouping. Commented Aug 4, 2014 at 8:25

4 Answers 4

6

One way is not using as many brackets:

t = (('a', 'b'), ) * 3

works just as well.

Sign up to request clarification or add additional context in comments.

Comments

2

The representation of that expression could be slightly simpler but it's almost canonical. I would use

t = 3 * (('a', 'b'), )

which removes one set of parentheses and visually warns about the multiplication before showing the tuple. You might imagine a further set of parentheses can be removed to give

t = 3 * ('a', 'b'),

but alas the result of this expression is not the required one, instead giving

(('a', 'b', 'a', 'b', 'a', 'b'),)

i.e. a tuple whose only element is the six generated elements.

Comments

1

You may try this:

t = (('a', 'b'),)*3

ie, simply remove the brackets and its done

Comments

1

Another choice:

from  itertools import repeat
tuple(repeat(('a', 'b'), 3))

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.