Python: Short way of creating a sequential list with a prefix

Question:

how can I generate a string (or Pandas series) like below:

a1,a2,a3,a4,...,a19

the following works, but I would like to know a shorter way

my_str = ""
for i in range(1, 20):
   comma = ',' if i!= 19 else ''
   my_str += "d" + str(i) + comma
Asked By: Emmet B

||

Answers:

You can just use a list comprehension to generate the individual elements (using string concatenation or str.format), and then join the resulting list on the separator string (the comma):

>>> ['a{}'.format(i) for i in range(1, 20)]
['a1', 'a2', 'a3', 'a4', 'a5', 'a6', 'a7', 'a8', 'a9', 'a10', 'a11', 'a12', 'a13', 'a14', 'a15', 'a16', 'a17', 'a18', 'a19']
>>> ','.join(['a{}'.format(i) for i in range(1, 20)])
'a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,a11,a12,a13,a14,a15,a16,a17,a18,a19'
Answered By: poke

What about:

s = ','.join(["a%d" % i for i in range(1,20)])
print(s)

Output:

a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,a11,a12,a13,a14,a15,a16,a17,a18,a19

(This uses a generator expression, which is more efficient than joining over a list comprehension — only slightly, with such a short list, however) This now uses a list comprehension! See comments for an interesting read about why list comprehensions are more appropriate than generator expressions for join.

Answered By: jedwards

Adding onto what poke said (which I found to be the most helpful), but bringing it into 2022:

[f'a{i}' for i in range(1, 21)]
Answered By: hNomad
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.