Apr-21-2019, 04:17 AM
Hello!
I cannot figure out something about negative indexes in that exercise of automate the boring stuff:
"
Comma Code:
Say you have a list value like this:
spam = ['apples', 'bananas', 'tofu', 'cats']
Write a function that takes a list value as an argument and returns a string with all the items separated by a comma and a space, with and inserted before the last item. For example, passing the previous spam list to the function would return 'apples, bananas, tofu, and cats'. But your function should be able to work with any list value passed to it."
Automate the boring link
I am trying for variation to save insert commas instead.
spam.insert(-1, ' and ') #insert and at the second to last position
Why not inserting at -2, that is the second to last? I spent quite a while thinking about it, I can't figure out why the negative index needs to be -1.
I cannot figure out something about negative indexes in that exercise of automate the boring stuff:
"
Comma Code:
Say you have a list value like this:
spam = ['apples', 'bananas', 'tofu', 'cats']
Write a function that takes a list value as an argument and returns a string with all the items separated by a comma and a space, with and inserted before the last item. For example, passing the previous spam list to the function would return 'apples, bananas, tofu, and cats'. But your function should be able to work with any list value passed to it."
Automate the boring link
I am trying for variation to save insert commas instead.
def listing(spam): for i in range (1,len(spam),2): spam.insert(i, ' ,') #inserting a comma with an offset of 2 spam.insert(-1, ' and ') #insert and at the second to last position, it has to be -1 and not -2, why? return spam spam = ['apples', 'bananas', 'tofu', 'cats'] print(listing(spam))The line that confuses me is 4:
spam.insert(-1, ' and ') #insert and at the second to last position
Why not inserting at -2, that is the second to last? I spent quite a while thinking about it, I can't figure out why the negative index needs to be -1.
