0

I am trying to create a custom transform for a list of lists. I am trying to run arithmetic operations on the sublist, but I am not successful. Here is my code:

def my_transform(seq):
    new_seq = []
    new_seq[0] = seq[0] + 100
    new_seq[1] = seq[1] - 1
    new_seq[2] = seq[2] * seq[2]
    return new_seq

my_list = [[1,2,3], [4,5,6]]

new_list = map(my_transform, my_list) # error
# ideal output:
#[[101,1,9], [104,4,36]]

But I get the following error:

Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
map(my_transform,my_list)
File "<pyshell#7>", line 3, in my_transform
new_seq[0] = seq[0] + 100
IndexError: list assignment index out of range

I also tried:

[my_transform(L) for L in my_list]

That gave me the same error, too. How can I get the results using map and/or list comprehension? Thanks!

Paul

3 Answers 3

4

The problem is in your function.

new_seq[0] tries to reference the first element of the list, but it's not there, so it gives the error. To fix this, we could make new_seq the length of the original list, or use append, but a much simpler solution would be to change the function so that it doesn't use an intermediate list at all.

def my_transform(seq):
    return [seq[0] + 100, seq[1] - 1, seq[2] * seq[2]]

If we try this function, we can see it works.

>>> my_list = [[1,2,3], [4,5,6]]
>>> map(my_transform, my_list)
[[101, 1, 9], [104, 4, 36]]
Sign up to request clarification or add additional context in comments.

1 Comment

Nice job pointing out there is no need for a new list like that.
2

The problem is that your new list starts out empty, which is why you get index errors trying to access items that don't exist, I've filled it with placeholder 0s to remedy this:

>>> my_list = [[1,2,3], [4,5,6]]
>>> def my_transform(seq):
        new_seq = [0] * len(seq)
        new_seq[0] = seq[0] + 100
        new_seq[1] = seq[1] - 1
        new_seq[2] = seq[2] * seq[2]
        return new_seq

>>> map(my_transform, my_list)
[[101, 1, 9], [104, 4, 36]]

Alternatively you can initialize to to a copy of seq like so:

new_seq = list(seq)

Comments

2

this is because the element 0, 1 and 2 are not defiend, you can write

def my_transform(seq):
    new_seq = []
    new_seq.append(seq[0] + 100)
    new_seq.append(seq[1] - 1)
    new_seq.append(seq[2] * seq[2])
    return new_seq

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.