Skip to content
Advertisement

Python: how to put ” ” on every string from a list

I have a list of all possible combinations of a 4-digit number and I want to put them in possible_comb = […]

But the list does not have any separator like a comma for example and it does not have the “..” per 4 digit number.

Example:

#This is my list

list = [ 0000 0001 0002 0003...9999] # no (,) and (") 

#expected

list = ["0000", "0001", "0002",..."9999"]

Putting ” and , manually is hellish. How to put “…” and , on every string from the list? Or are there any other ways to list all possible 4 digit numbers and put it in a list as a string?Thanks.

Advertisement

Answer

You can make a list like this with a list comprehension by converting integers to strings and using zfill() to pad with zeros:

l = [str(n).zfill(4) for n in range(10000)]

l will be:

['0000',
 '0001',
 '0002',
 '0003',
 '0004',
 '0005',
 ...
 '9999'
 ]

Depending on how you are using it you might be better off with a generator expression.

l = (str(n).zfill(4) for n in range(10000))
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement