views:

119

answers:

3

This question is just out of general curiosity. I've just noticed it when working on my current project (surprisingly I haven't came across before today).

Take this code:

List = ["hi","stack","over","flow","how","you","doing"]
del List(len(List)-1)

Error:

SyntaxError: can't delete function call

I don't understand why you aren't allowed to delete an index of a list by referencing a call to a function? Do I just shut up and accept you can't do it or am I doing something fundamentally wrong?

I apologise if there is an easy answer to this but either Google is getting less helpful or this is so blatantly obvious I need help.

+4  A: 

You are calling a function List() when you should be indexing a list, List[].

In Python, Round parenthesis, (), are used to call functions, while square brackets, [] are used to index lists and other sequences.

Try:

del List[len(List) - 1]

or even better, use the fact that Python allows negative indexes, which count from the end:

del List[-1]

Also, you might want to make the list's name not so close to the built-in list type name, for clarity.

unwind
Oh for the love of God, I feel like an idiot. Thanks a lot!
day_trader
List[len(List) - 1] is not "pythonic", you want to do List[-1] as jleedev suggests.
Kimvais
@Kimvais: good point, I added that.
unwind
+10  A: 

You meant to delete the last element of the list, not somehow call List as a function:

del List[len(List)-1]

Python's del statement must take specific forms like deleting a variable, list[element], or object.property. These forms can be nested deeply, but must be followed. It parallels the assignment statement -- you'll get a similar syntax error if you try to assign to a function call.

Of course, what you really want in this case is

del List[-1]

which means the last element of the list, and is way more Pythonic.

jleedev
+1: Delete might work with a call to a function, but the example is obviously an object named List. Not a function named List.
S.Lott
Nope, it's a syntax error regardless. The simplest form "del x" means delete the name "x". "del x[y]" and "del x.y" send various messages to the object x with y as the parameter. While you might come up with a valid use case to define "del x(y)", it's not Python.
jleedev
+1  A: 

You are allowed. However, you are using the wrong syntax. Correct syntax is:

del List[-1]

Notice that the "len(List) part is useless.

Lennart Regebro