Create tuple of multiple items n Times in Python -


a list can created n times:

a = [['x', 'y']]*3 # output = [['x', 'y'], ['x', 'y'], ['x', 'y']] 

but want make tuple in such way not returning similar result in list. doing 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.

the outer parentheses grouping parentheses. need add comma make outer enclosure tuple:

a = (('x','y'),)*4 print(a) # (('x', 'y'), ('x', 'y'), ('x', 'y'), ('x', 'y')) 

for context, wouldn't make sense tuple while doing f = (x + y), example.


in order define singleton tuple, comma required:

a = (5)  # integer = (5,) # tuple = 5,   # tuple, parens not compulsory 

on side note, duplicating items across nested containers require more simple mult. operation. consider first operation example:

>>> = [['x', 'y']]*3 >>> # modify first item ... >>> a[0][0] = 'n' >>> [['n', 'y'], ['n', 'y'], ['n', 'y']] 

there no first item - parent list contains 1 list object duplicated across different indices. might not particularly worrisome tuples immutable way.

consider using more correct recipe:

>>> = [['x', 'y'] _ in range(3)] >>> a[0][0] = 'n' >>> [['n', 'y'], ['x', 'y'], ['x', 'y']] 

Comments

Popular posts from this blog

php - How to display all orders for a single product showing the most recent first? Woocommerce -

asp.net - How to correctly use QUERY_STRING in ISAPI rewrite? -

angularjs - How restrict admin panel using in backend laravel and admin panel on angular? -