-2

I am trying to write a function that takes an array, converts it to a string, then appends it together.

Ex. [1,2,3,4,5,6] would return '123456'.

Here is the code that I tried already, but it gives me the error "list indices must be integers, not str"

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

def add_it_up(a,b):
    return a+b

def to_str(a):
    for i in a:
        a[i] = str(a[i])

    reduce(add_it_up, a)

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

def to_str(a):

    ''.join(map(str, l))
    return a

what is wrong with the above code? it is just returning the original a value.

arshajii
  • 127,459
  • 24
  • 238
  • 287
Matt Walker
  • 171
  • 1
  • 4
  • 12
  • 1
    possible duplicate of [Joining List has integer values with python](http://stackoverflow.com/questions/3590165/joining-list-has-integer-values-with-python) – Viktor Kerkez Sep 20 '13 at 14:11

4 Answers4

10

Don't reinvent the wheel:

>>> l = [1,2,3,4,5,6]
>>> 
>>> ''.join(map(str, l))
'123456'

The problem in your code is that for loops in Python are really for-each loops. So when you have something like for i in a, i takes on all of the elements of a, not the indices of a.

So, your loop actually works fine for one iteration, and you successfully set an element of your list to a string (specifically, the element at index 1, since that's the first value of i). However, the next i will reference this new string element and will consequently cause an error when you do a[i].

This is an interesting phenomenon, so let's look at this with the simplified list a = [1,2,3], which is a sublist of your a and just enough to see where and why the error takes place:

+-----+-----+-----+
|  1  |  2  |  3  |
+-----+-----+-----+
   ^
   i (loop starts, i takes on first value of list: 1)

+-----+-----+-----+
|  1  | '2' |  3  |
+-----+-----+-----+
   ^
   i (we set element at index i (a[1]) to str(a[1]), which is '2')

+-----+-----+-----+
|  1  | '2' |  3  |
+-----+-----+-----+
         ^ 
         i (next iteration, i takes on second value: '2')

Error occurs with a[i], list indices must be integers.

Reference

arshajii
  • 127,459
  • 24
  • 238
  • 287
  • I'm new to python, what is map & join? – Matt Walker Sep 20 '13 at 14:09
  • @MattWalker I added some references. – arshajii Sep 20 '13 at 14:12
  • `map` takes some function (in this case the function is `str`) and applies it to each element of some list. The `.join` method of a string takes a list, and inserts the given string between each element of that list. For more details, google "python map" and "python join". – SethMMorton Sep 20 '13 at 14:12
  • I see what you did @arshajii, however when i try to add it into my function to_str(a), and define a as [1,2,3,4,5...], the function just returns a – Matt Walker Sep 20 '13 at 14:23
  • @MattWalker You can `def add_it_up(a,b): return str(a) + str(b)` and then `reduce(add_it_up, a)`, if you want to continue with your approach. – arshajii Sep 20 '13 at 14:29
  • @MattWalker The code you just posted doesn't work because you're not modifying `a`. You can just `return ''.join(map(str, l))`, though. – arshajii Sep 20 '13 at 14:31
1

You could have done it with join and list comprehensions

''.join([str(_) for _ in a])

Even better (thanks chepner)

''.join(str(_) for _ in a)
Cyrille
  • 13,905
  • 2
  • 22
  • 41
  • 2
    `join` doesn't require a list, just an iterable. A bare generator is fine. – chepner Sep 20 '13 at 14:17
  • I like this the best, except that it doesn't work as the OP requested -- you forgot the commas. Try: ','.join((str(_) for _ in a)) – NVRAM Sep 20 '13 at 14:25
1

This one should work:

>>> t =[1,2]
>>> s=[3,4]
>>> ''.join(str(a) for a in t + s)
'1234'
>>>

The official docs provide a good explanation for join. After reading the generators explanation , you should get a feeling about its power :-)

Robert Caspary
  • 1,584
  • 9
  • 7
0

it gives me the error "list indices must be integers, not str"

occurs because

for i in a:

iterates over the elements in a. The first time through the loop, i takes the value 1 so it does

a[1] = str(a[1])

which changes a to

[1,"2",3,4,...]

then the next time through the loop i gets a[1] which is now the string '2', and it tries

a["2"] = str(a["2"])

which fails because you can't index a Python list with a string.


Others have explained how to solve your particular problem, but in general, to iterate over the indices of a list, try

for i in xrange(0, len(a)):
  ...
Mike Samuel
  • 118,113
  • 30
  • 216
  • 245