kaushik
kaushik

Reputation: 5969

problem with lists?

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?

Upvotes: 1

Views: 179

Answers (4)

miku
miku

Reputation: 188004

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:

Upvotes: 4

Felix
Felix

Reputation: 142

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)]  

Upvotes: 3

lowerkey
lowerkey

Reputation: 8325

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

Upvotes: 0

SilentGhost
SilentGhost

Reputation: 319551

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).

Upvotes: 11

Related Questions