On 29Mar2015 00:34, boB Stepp <[email protected]> wrote:
I am puzzled by the following:

Python 3.4.3 (v3.4.3:9b73f1c3e601, Feb 24 2015, 22:44:40) [MSC v.1600
64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
a_list = [5, 0, 2, 4, 1]
print(a_list.sort())
None
print(a_list)
[0, 1, 2, 4, 5]


I expected the first print statement to return what the second one
did. Apparently the first print printed a_list, then did the sort. Why
is this so?

Both prints are as expected: they are printing the value of the expressions inside the parentheses.

So: taking the latter print first:

 print(a_list)

it is printing a_list, as you might expect after the sort.

The former print:

 print(a_list.sort())

is printing the result of "a_list.sort()".

Like most Python functions that operate on something (i.e. .sort, which sorts the list in place), the .sort method returns None. And that is printed.

Try running the expressions themselves, discarding the "print". In the interactive interpreter, each expression you type in has its results printed unless the result is None. So, in Python 3.4.3 here:

 Python 3.4.3 (default, Mar 10 2015, 14:53:35)
 [GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.56)] on darwin
 Type "help", "copyright", "credits" or "license" for more information.
 >>> a_list = [5, 0, 2, 4, 1]
 >>> a_list.sort()
 >>> a_list
 [0, 1, 2, 4, 5]
 >>>

The assignment has no return value.
The .sort() call returns None, so the interpreter prints nothing.
The expression "a_list" is of course the list, which is printed.

Just to be glaingly obvious about this aspect of the interactive interpreter:

 >>> x=1
 >>> x
 1
 >>> x=None
 >>> x
 >>>

Cheers,
Cameron Simpson <[email protected]>

You are just paranoid, and all your friends think so too.
       - James Joseph Dominguez <[email protected]>
_______________________________________________
Tutor maillist  -  [email protected]
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor

Reply via email to