1

I wanted to add in list years from 0000 to 9999, what I did:

i = 0
a = []

while i <= 9:
    a += [i]
    i += 1
years = []
for i1 in a: 
    for i2 in a:
        for i3 in a:
            for i4 in a:
                numbers = f'{i1}{i2}{i3}{i4}'
                years += [numbers]

But what if I need do this 99 times? Is exist any way to do this without simple copypasting code?

3
  • Do you simply want a list with numbers from 0000 to 9999 in it times 99 ? Commented Oct 9, 2019 at 13:42
  • @rite2hhh yes, as an example Commented Oct 9, 2019 at 13:44
  • Then, you should use the most rudimentary principles in python, and do this- python3: ["{:04}".format(i) for i in range(10000)], It will create a list of list with numbers represented as strings from 0000 to 9999. if you want 99 such lists, there's may ways to do it. One of them is to create a list of lists. [["{:04}".format(i) for i in range(10000)] for i in range(99)] Commented Oct 9, 2019 at 15:36

2 Answers 2

1

What you want is called a *cartesian product.

from itertools import product

for numbers in product([1,2,3], repeat=5): ...

However, this increases exponentially with the number of loops, and you should probably rethink what you're trying to do.

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

Comments

0

This uses the zfill function to fill the rest of the left portion with zeros for a string . for n = 2 it prints from 00 to 99 which is shown below and for n = 4 it produces the same output as your program.

output = []
n=2
for i in xrange(0,10**n):
    output.append(str(i).zfill(n))
print(output)

OUTPUT

['00', '01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31', '32', '33', '34', '35', '36', '37', '38', '39', '40', '41', '42', '43', '44', '45', '46', '47', '48', '49', '50', '51', '52', '53', '54', '55', '56', '57', '58', '59', '60', '61', '62', '63', '64', '65', '66', '67', '68', '69', '70', '71', '72', '73', '74', '75', '76', '77', '78', '79', '80', '81', '82', '83', '84', '85', '86', '87', '88', '89', '90', '91', '92', '93', '94', '95', '96', '97', '98', '99']

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.