Python Forum

Full Version: Automate the boring stuff, inserting commas in list
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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.

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. Sick
spam.insert(i, 'and') inserts at index min(len(spam), i) when i is non negative and at index max(0, len(spam) + i) when i is negative.
(Apr-21-2019, 04:50 AM)Gribouillis Wrote: [ -> ]spam.insert(i, 'and') inserts at index min(len(spam), i) when i is non negative and at index max(0, len(spam) + i) when i is negative.

Sorry, I don't get it...
(Apr-21-2019, 04:17 AM)DJ_Qu Wrote: [ -> ]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. Sick

When in doubt, it's always good to start with built-in help:

>>> help(list.insert)
Help on method_descriptor:

insert(self, index, object, /)
    Insert object before index.
(END)
I think that this is quite straightforward explanation.

Why is it so? Try to answer the question: how to insert something before first element which happens to have index 0? There is no index that can represent that position... This ain't replace method which replaces element on specific index.