[Tutor] longest common substring

Andreas Perstinger andreas.perstinger at gmx.net
Sat Nov 12 17:40:38 CET 2011


On 2011-11-12 16:24, lina wrote:
> Thanks, ^_^, now better.

No, I'm afraid you are still not understanding.

> I checked, the sublist (list) here can't be as a key of the results (dict).

"result" isn't a dictionary. It started as an empty list and later 
becomes a null object ("NoneType").

You must not forget that you are inside a for-loop. Simplified your 
situation is like this:

 >>> result = []
 >>> for i in range(1,10):
...     print("Iteration {0}, result = {1}".format(i, result))
...     result = result.append(i)
...
Iteration 1, result = []
Iteration 2, result = None
Traceback (most recent call last):
   File "<stdin>", line 3, in <module>
AttributeError: 'NoneType' object has no attribute 'append'

As you see the error happens in the *second* iteration, because result 
is no list any more.
Dave gave you already the explanation: functions and method always 
return a value in Python. If the don't have a return statement they 
return "None".

Another simple example:

 >>> a = print("Test")
Test

"print" is a function which prints out the text you passed to it and you 
usually aren't interested in its return value. But every function/method 
in Python returns something. You save this value in "a"

 >>> print(a)
None

As you see the return value of "print" is "None".

 >>> a.append(x)
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'append'

Same error as above, because "NoneType" objects (null objects) don't 
have a method "append".

I also think you mix two different ways to add an element to a list:

result.append(x)

is equivalent to

result = result + [x] (that's what you will use in other languages)

HTH, Andreas


More information about the Tutor mailing list