Python Forum

Full Version: Question on Tuple
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello Users,

I have my desired Tuple (see below) using the code mentioned. But I was wondering if there is any other clean way to obtain the same Output? (without using For/While Loops)

Desired Output:

((5, 5, 5, 5, 5, 5), (5, 5, 5, 5, 5, 5), (5, 5, 5, 5, 5, 5), (5, 5, 5, 5, 5, 5), (5, 5, 5, 5, 5, 5), (5, 5, 5, 5, 5, 5))

Used Code:

Ar_tuple=()
Mat_tuple=()
 
i=0
while i<6:
    Ar_tuple=(Ar_tuple + (5,)) 
    i=i+1                

j=0
while j<6:
    Mat_tuple=((Mat_tuple)+(Ar_tuple,)) 
    j=j+1
    
print(Mat_tuple)
Best Regards
((5,) * 5,) * 6
Note that this does not work well with lists. Lists are mutable, so instead of a list of six distinct sub-lists you will get a list of six references to the same list. It works with tuples because they are immuntable.
lcome to Termux!

Wiki:            https://wiki.termux.com
Community forum: https://termux.com/community
IRC channel:     #termux on freenode
Gitter chat:     https://gitter.im/termux/termux
Mailing list:    [email protected]

Search packages:   pkg search <query>
Install a package: pkg install <package>
Upgrade packages:  pkg upgrade
Learn more:        pkg help
$ ipython
Python 3.7.2 (default, Jan 16 2019, 21:05:09)
Type 'copyright', 'credits' or 'license' for more information
IPython 7.2.0 -- An enhanced Interactive Python. Type '?' for help.

In [1]: from itertools import repeat

In [2]: list(repeat(repeat(5,3), 4))
Out[2]: [repeat(5, 3), repeat(5, 3), repeat(5, 3), repeat(5, 3)]

In [3]: list(repeat(tuple(repeat(5,3)), 4))
Out[3]: [(5, 5, 5), (5, 5, 5), (5, 5, 5), (5, 5, 5)]

In [4]: