You actually don’t need to return anything!
This exercise asks you to create a function, such that:
The function should append the size of lst
(inclusive) to the end of lst
. The function should then return this new list.
Considering the solution:
def append_size(lst):
lst.append(len(lst))
return lst
… I think that the exercise has two objectives:
- to provide practice with the list.append() method
- to show that you can often omit an intermediate variable such as
length = len(lst)
, but rather just use an expression as a parameter in a method (or function) call.
For some reason, however, by asking for a return value, it obscures the most interesting fact of all: The list.append() modifies the list it is appending to, so there is no need for a return statement.
Here, I will simply append the string ‘x’ to a list:
def append_x(lst):
lst.append('x')
return lst
my_lst = ['a', 'b', 'c']
print(append_x(my_lst))
print(my_lst)
# Output
['a', 'b', 'c', 'x']
['a', 'b', 'c', 'x']
The original list, my_list has changed. So why bother with a return statement?
def append_x(lst):
lst.append('x')
# return lst
my_lst = ['a', 'b', 'c']
print(append_x(my_lst)) # this will print None, but it does run the function
print(my_lst)
# Output
None # absent an explicit return statement, the function returns None
['a', 'b', 'c', 'x']