tags:

views:

109

answers:

4
j=0
x=[]
for j in range(9):
  x=x+ [j]

this will output

[1,2,3,4,5,6,7,8,9]

i wanted it as

['1','2','3'...

how can I get it?

+12  A: 

convert to string:

>>> [str(i) for i in range(9)]
['0', '1', '2', '3', '4', '5', '6', '7', '8']

if you want your list to start with 1 just change your range function:

>>> [str(i) for i in range(1, 9)]
['1', '2', '3', '4', '5', '6', '7', '8']

Also, you don't need to initialise loop variable (j=0 is not required).

SilentGhost
+4  A: 

Python 2

>>> map(str, range(1, 9))
['1', '2', '3', '4', '5', '6', '7', '8']

Python 3

>>> list(map(str, range(1, 9)))
['1', '2', '3', '4', '5', '6', '7', '8']

Documentation for range:

The MYYN
Note that, on Py3k this will return lazily as `<map object at 0x????>`. One needs to evaluate to a list with `list(map(str, range(9)))`.
KennyTM
Thanks for the update.
The MYYN
A: 
j=0
x=[]
for j in range(9):
    x=x+[str(j)]
Joshua Moore
+3  A: 

Ok, the "good" python ways are already posted, but I want to show you how you would modify your example to make it work the way you want it:

j=0  
x=[]  
for j in range(9):  
   x = x + [str(j)]  
Felix
Rule of Clarity: Clarity is better than cleverness.
Anders
I might argue that `x.append(str(j))` is more clear than the `+` operator.
tgray