-1

Here I am trying to convert a string into list without using any inbuilt functions like 'list' or 'split' but .append() or .insert() functions are not adding elements to the list

r=[]
x='abcd'
for i in xrange(0,len(x)):
    print x[i]
    r=r.insert(0,x[i])
    print r
swapnil
  • 21
  • 1
  • 8

2 Answers2

1

The insert() function doesn't return anything. It changes the list, so you need not assign it to r, which is wrong.

You can write like,

>>> r=[]
>>> r.insert(0, 'a')
>>> r
['a']
nu11p01n73R
  • 26,397
  • 3
  • 39
  • 52
0

The methods are adding elements to the list, that is the problem with your code! However, the methods return None, not a list. So, the following should work:

r=[]
x='abcd'
for i in xrange(0,len(x)):
    print x[i]
    r.insert(i,x[i])
    print r

The above gives the following output:

a
['a']
b
['a', 'b']
c
['a', 'b', 'c']
d
['a', 'b', 'c', 'd']

Also note that to use the insert method you would want to insert at i not at zero every time, unless you wanted to build a list in reverse order of the original string. Indeed, if you want to build a list in the original order, it is better to just use .append

juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172