In addition to other answers, I would also suggest to use slicing notation [:]
when dealing with lists to prevent getting list index out of range
errors in case there is no item:
def dup_last(data):
data.append(data[-1])
return data
The above function will raise IndexError
if data
is empty list:
>>> print dup_last([])
----> 2 data.append(data[-1])
3 return data
4
IndexError: list index out of range
When you update your function as follows, you no longer get that kind of error:
def dup_last(data):
data.extend(data[-1:])
return data
>>> print dup_last([])
[]
>>> print dup_last([1])
[1, 1]
>>> print dup_last([1, 2])
[1, 2, 2]
There is a good explanation in this SO question about how slicing works in Python.