+ 11

More efficient way in Pyhton ?

Say I have a code for i in range(10): for j in range(10): for k in range(10): print(i,j,k) If someday I want more than i,j,k it would be quite bothersome using this, so is there any other efficient way for this? Thank You!

21st Jun 2018, 9:04 PM
Muhammad Hasan
Muhammad Hasan - avatar
7 Answers
+ 13
Here's a simpler one without using a list comprehension: n=3 for i in range(10**n): print(" ".join("{:0{z}}".format(i, z=n))) edit: added some explanation, hopefully helpful =========================================== if you have three slots, you're counting from 000-999 (1000 values, or 10*10*10, or 10^3) for i in range(10**3) # count from 0 to 999 The leading 0 and number in the format string controls zero-padding: "{:02}".format(1) would print "01" "{:03}".format(1) would print "001" I'm using the substitution z=n to send in the value of n {:0{z}} is the same as {:03} when z=n and n=3 For some reason I can't just use n. The output of format() is a string. Any string is automatically iterable as a list. for c in "123": print(c) # prints 1 then 2 then 3 " ".join(string) takes every element of a list (here, a string) and joins them with spaces: " ".join("123") is "1 2 3"
21st Jun 2018, 11:01 PM
Kirk Schafer
Kirk Schafer - avatar
+ 10
Thanks a lot 👍 Kirk Schafer If I could upvote multiple times I would do so
21st Jun 2018, 11:15 PM
Muhammad Hasan
Muhammad Hasan - avatar
+ 8
n=3 for i in range(10**n): print(*str(i).zfill(n)) #This is working too
24th Jun 2018, 6:39 PM
Mert Yazıcı
Mert Yazıcı - avatar
+ 7
Thanks I will try to comprehend your way
21st Jun 2018, 11:03 PM
Muhammad Hasan
Muhammad Hasan - avatar
+ 3
This is just counting in base 10 for three slots. I'm hoping to come up with something simpler, but this works. n=3 print(*map(" ".join, ["{:0{z}}".format(i, z=n) for i in range(10**n)]), sep="\n")
21st Jun 2018, 10:51 PM
Kirk Schafer
Kirk Schafer - avatar
+ 1
Kirk Schafer beautifully written 👍
22nd Jun 2018, 1:02 AM
Anthony Perez
+ 1
this was helpful to me also
23rd Jun 2018, 7:54 AM
Alex
Alex - avatar