0

I am new to python and learning from CodeAcademy.com; I have a problem:

Change list_function so that:

  1. Add 3 to the item at index one of the list.
  2. Store the result back into index one.
  3. Return the list.

Here is my code:

def list_function(x):
    return x

n = [3, 5, 7]
n.insert(1,3)
print list_function(n)

I get only the error, what should i do?

My problem is to understand the number 2 and 3 option.

10
  • I don't see any errors here. Commented Jan 15, 2015 at 8:40
  • If you're using python 3 I think you need to use print with function syntax i.e print(list_function(n)) Commented Jan 15, 2015 at 8:41
  • @JohnGreenall: lets confuse the user some more. Commented Jan 15, 2015 at 8:43
  • @MartijnPieters - trying to be helpful! when I tried following a dive into python tutorial years ago I was using python 3 and got stuck for half an hour wondering why i couldn't get "hello world" to work! Commented Jan 15, 2015 at 8:45
  • 1
    @MarounMaroun: ah, yes, misunderstood what you meant. You may want to be explicit about please post the error you got here next time. CodeAcademy gives the student a message that their solution is wrong, I believe, but there was no Python exception here. Commented Jan 15, 2015 at 9:04

1 Answer 1

2

You are confusing adding with inserting, point 1:

  1. Add 3 to the item at index one of the list.

You interpreted this as insertion:

n.insert(1,3)

but really they meant the arithmetic operation:

n[1] + 3

This adds 3 (with +) tot the item at index one ([1]) of the list (n).

You then insert that back into the list at the same index:

n[1] = n[1] + 3

All this should be done inside your function:

def list_function(some_list):
    some_list[1] = some_list[1] + 3  # step 1 and 2
    return some_list                 # step 3
Sign up to request clarification or add additional context in comments.

1 Comment

Spot on; the question was triggered by the overloaded meaning of add. For the record, if you are willing to combine step 1 and 2 into a single statement you might consider using some_list[1] += 3 (though this might be considered 'less explicit' about what's going on).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.