Reputation: 29
I'm trying to add the last item of a list onto the list my code is:
def dup_last(data):
data.append([-1])
return data
and calling for the function is:
item = dup_last([1,2,3])
print(item)
but I want my output to be within only one set of brackets like:
[1, 2, 3, 3]
Upvotes: 1
Views: 253
Reputation: 52203
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.
Upvotes: 2
Reputation: 12022
You need to do data.append(data[-1])
; data.append([-1])
appends a value which is a list containing only -1
, so your result will be [1, 2, 3, [-1]]
.
Note that this will modify the list in-place, so whichever list you pass in will also have the last element duplicated, not just the list you get out (though they could be the same list).
I wouldn't use a function for this; just do data.append(data[-1])
instead of data = dup_last(data)
, or even dup_last(data)
. Also, it's probably better to just add the duplicate manually if you're working with a list literal; data = [1, 2, 3, 3]
vs data = dup_last([1, 2, 3])
or similar.
Upvotes: 1
Reputation: 122493
data.append([-1])
Here you are appending [-1]
, a list with an element of -1
, change it to:
data.append(data[-1])
Upvotes: 3