When you pass a list to a function, the function gets a reference to the list. If the function modiﬁes a list parameter, the caller sees the change. For example, delete_head removes the ﬁrst element from a list:
def delete_head(t): del t[0]
Here’s how it is used:
>>> letters = ['a', 'b', 'c']>>> delete_head(letters)>>> printiﬁes a list, but the + operator creates a new list:
>>> t1 = [1, 2] >>> t2 = t1.append(3) >>> print t1 [1, 2, 3] >>> print t2 None >>> t3 = t1 + [4] >>> print t3 [1, 2, 3, 4] ﬁrst element of a list:
def tail(t): return t[1:]
This function leaves the original list unmodiﬁed. Here’s how it is used:
>>> letters = ['a', 'b', 'c']>>> rest = tail(letters)>>> print rest['b', 'c']
- 751 reads