0

I'm trying to write function map() getting error IndexError: list index out of range

     def map1(fn, a):
         i = 0
         b = []
         while i != len(a):
             print(len(a))
             i += 1
             b.append(fn(a[i]))
         return b

with working function

    def translate(x):
        dicti = {"merry": "god", "christmas": "jul", "and": "och", "happy": "gott", "new": "nytt", "year": "år"}
        return dicti[x]

got the error

     IndexError: list index out of range
1
  • Please post a full stacktrace of the IndexError so that it is possible to see where it occurs. What are the arguments to map1() that produce the error? Commented Mar 10, 2015 at 13:53

2 Answers 2

1

You increment i before accessing a. In the last iteration, i is len(a)-1 at the beginning of the loop body, then it is incremented to len(a), but this is just outside the valid index range. To fix it, you have to increment after the access:

while i != len(a):
    b.append(fn(a[i]))
    i += 1

However, an improved way to do this, is to use range, which produces the correct values for i for you automatically:

for i in range(len(a)):
    b.append(fn(a[i]))

An even better way is to iterate over the entries of a directly:

for x in a:
    b.append(fn(x))

An even better way is to use a list comprehension:

b = [fn(x) for x in a]
Sign up to request clarification or add additional context in comments.

2 Comments

That worked when I used it, although I'm not sure how to set it up with the last line of code you posted...
Instead of: def map1(fn, a): b = []; ...; return b, you do: def map1(fn, a): b = [fn(x) for x in a]; return b, or simply def map1(fn, a): return [fn(x) for x in a]
1

You where increasing i before using it.

def map1(fn, a):
         i = 0
         b = []
         while i != len(a):
             print(len(a))

             b.append(fn(a[i]))
             i += 1
         return b

def translate(x):
        dicti = {"merry": "god", "christmas": "jul", "and": "och", "happy": "gott", "new": "nytt", "year": "ar"}
        return dicti[x]

map1(translate, ["merry", "and"])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.