Reputation: 33
I am trying to define a function where: This function takes a single argument which is a list name itself. It will then look at the value of the last existing item in the list, it will then append a new value that is one unit bigger. This is what I have:
my_list = [ 1, 2, 3, 4, 5 ]
def add_item_to_list(ordered_list):
for (num[-1]) in ordered_list:
ordered_list.append(num[-1] + 1)
# Appends new item to end of list with the value (last item + 1)
But I get this error:
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in add_item_to_list
NameError: name 'num' is not defined
Upvotes: 0
Views: 70
Reputation: 18106
You need no for-loop
:
my_list = [ 1, 2, 3, 4, 5 ]
def add_item_to_list(ordered_list):
ordered_list.append(ordered_list[-1] + 1)
return ordered_list
print(add_item_to_list(my_list))
Output:
[1, 2, 3, 4, 5, 6]
Upvotes: 2
Reputation: 39354
You can have code which does as you describe
def add_item_to_list(ordered_list):
last_item = ordered_list[-1]
ordered_list.append(list_item + 1)
Upvotes: 1