0

I would like to create a list with a variable part :

mylist = ['a1','a2','a3','a4','a5']

I am trying :

i = range(1,5)
ii = [str(x) for x in i]

which works, and then I would like to do :

mylist = list('a' + x for x in ii)

but that doesn't work

salim
  • 321
  • 1
  • 2
  • 12

1 Answers1

0

Ranges are half-open in Python so you must use xrange(1,6), and although concatenation is fine (between two strings) you could also use str.format. You can iterate over the numbers and append them to a in one go in a list comprehension with xrange ( see xrange vs range) such that you don't need to create two temporary lists in the process as you did:

>>> [str.format('a{0}', x) for x in xrange(1,6)]
['a1', 'a2', 'a3', 'a4', 'a5']
>>> ['a' + str(x) for x in xrange(1,6)]
['a1', 'a2', 'a3', 'a4', 'a5']
Community
  • 1
  • 1
miradulo
  • 28,857
  • 6
  • 80
  • 93