Python Newbie
Python Newbie

Reputation: 21

Python 3 Error Missunderstanding (IndexError)

Here's my code

def abc(l,z):
    L=[]
    länge= len(L)
    for x in range(0, länge+1):
        L[x]+z
        print(L)

abc(["1","2","3"],"-")

I want the program to output "1-2-3"

l in abc(l,z) should be a List out of Strings which combines "l" and "z" to a single String.

I'm getting an Index Error: list index out of range.

Upvotes: 0

Views: 41

Answers (1)

timgeb
timgeb

Reputation: 78700

There are a couple of issues here.

First, range(0, länge+1) will stop at länge but your list only has indexes from 0 to
länge - 1, so that's one source for an IndexError.

Second, L[x]+z will give you another IndexError because L is empty but you try to access L[0] (and in the next iteration, where you don't get because of the error, L[1], L[2], and so on).

Third, even without an IndexError the statement L[x]+z will do nothing. You compute the value of L[x]+z but then you don't assign any variable to it, so it is immediately lost.

Fourth, in order to print your final result, put the call to print after the for loop, not inside. Consider using return instead of print if you actually want to do something with the result the function produces (make sure to educate yourself on the difference between print and return).

Fifth, you want to build a string, so the usage of the list L does not make much sense. Start with an empty string and add the current item from l and z to it in the loop body (coupled with a re-assignment in order to not lose the freshly computed value).

Lastly, there's no point in using range here. You can iterate over values in a list direclty by simply writing for x in l:.

That should give you enough to work with and fix your code for now.

(If you don't care why your function does not work and this is not an exercise, simply use str.join as suggested in the comments.)

Upvotes: 2

Related Questions