Error in Python Tutorial
In The Python Tutorial (version 3.8.2), the end of Section 4.6 "Defining Functions" reads: The method append() shown in the example is defined for list objects; it adds a new element at the end of the list. In this example it is equivalent to result = result + [a], but more efficient. This statement is inaccurate. The append() method operates on the object, whereas the assignment statement creates a new list by copying the existing list and appending the new list. The difference is demonstrated with the following example (in IDLE):
def example(x):
print(x) x.append('b') print(x) x = x + ['a'] print(x)
a=[] example(a) [] ['b'] ['b', 'a'] a ['b']
As can clearly be seen, the append() method modified the list argument which was passed by reference to the function example() whereas the assignment created a new list which detached the local variable x from the list passed as an argument.
Correction. The + operator is responsible for creating a new list. Compare the quoted statement with the equivalence given for the append() method at the start of Section 5.1, "More on Lists": Equivalent to a[len(a):] = [x]. On Mon, Apr 20, 2020 at 8:01 PM Israel Pinkas <pinkas613@gmail.com> wrote:
In The Python Tutorial (version 3.8.2), the end of Section 4.6 "Defining Functions" reads:
The method append() shown in the example is defined for list objects; it adds a new element at the end of the list. In this example it is equivalent to result = result + [a], but more efficient.
This statement is inaccurate. The append() method operates on the object, whereas the assignment statement creates a new list by copying the existing list and appending the new list. The difference is demonstrated with the following example (in IDLE):
def example(x):
print(x)
x.append('b')
print(x)
x = x + ['a']
print(x)
a=[] example(a) [] ['b'] ['b', 'a'] a ['b']
As can clearly be seen, the append() method modified the list argument which was passed by reference to the function example() whereas the assignment created a new list which detached the local variable x from the list passed as an argument.
participants (1)
-
Israel Pinkas