I am out of trial and error again Lists

Steven D'Aprano steve+comp.lang.python at pearwood.info
Thu Oct 23 02:05:08 CEST 2014


Seymore4Head wrote:

> Those string errors were desperate attempts to fix the "append" error
> I didn't understand.

Ah, the good ol' "make random changes to the code until the error goes away"
technique. You know that it never works, right?

Start by *reading the error message*, assuming you're getting an error
message. I'm the first person to admit that Python's error messages are not
always as clear as they should be, especially syntax errors, but still
there is a lot of information that can be gleamed from most error messages.
Take this attempt to use append:

py> mylist.append(23)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'mylist' is not defined

That tells me that I have forgotten to define a variable mylist. So I fix
that:

py> mylist = 23
py> mylist.append(23)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'int' object has no attribute 'append'


That tells me that I can't append to a int. After googling for "Python
append" I learn that I can append to a list, so I try again:

py> mylist = []
py> mylist.append(23)
py> print(mylist)
[23]


Success!

If you are familiar with other programming languages, it might help to think
of append() as being like a procedure in Pascal, for example. You call
append() with an argument, but don't expect a return result.

Technically, *all* functions and methods in Python return something, even if
just the special value None, which can lead to "Gotchas!" like this one:

py> mylist = mylist.append(42)  # Don't do this!
py> print(mylist)  # I expect [23, 42] but get None instead.
None

Oops. One of the small annoyances of Python is that there is no way to tell
ahead of time, except by reading the documentation, whether something is a
proper function that returns a useful value, or a procedure-like function
that returns None. That's just something you have to learn.

The interactive interpreter is your friend. Learn to experiment at the
interactive interpreter -- you do know how to do that, don't you? If not,
ask. At the interactive interpreter, if a function or method returns a
value, it will be printed, *except for None*. So a function that doesn't
print anything might be procedure-like, and one which does print something
might not be:

py> mylist = [1, 5, 2, 6, 4, 3]
py> sorted(mylist)  # proper function returns a value
[1, 2, 3, 4, 5, 6]
py> mylist.sort()  # procedure-like function returns None
py> print(mylist)  # and modifies the list in place
[1, 2, 3, 4, 5, 6]


-- 
Steven




More information about the Python-list mailing list