Python Forum
Automate the boring stuff, inserting commas in list
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Automate the boring stuff, inserting commas in list
#1
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
Reply


Messages In This Thread
Automate the boring stuff, inserting commas in list - by DJ_Qu - Apr-21-2019, 04:17 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Commas issue in variable ddahlman 6 505 Apr-05-2024, 03:45 PM
Last Post: deanhystad
  help with commas in print functions kronhamilton 11 3,539 Feb-10-2022, 02:02 PM
Last Post: mishraakash
  Run the code for some stuff it does not return me why Anldra12 3 2,890 Apr-19-2021, 02:01 PM
Last Post: Anldra12
  "Automate the Boring Stuff with Python" creating a path works but only for CMD promt Milos 2 2,904 Nov-28-2020, 01:08 PM
Last Post: Larz60+
  Unable to print stuff from while loop Nick1507 4 2,386 Sep-17-2020, 02:26 PM
Last Post: Nick1507
  How Do I Install Stuff for Python? CopBlaster 6 3,253 May-08-2020, 12:27 PM
Last Post: hussainmujtaba
  Learning to have Class and doing stuff with it... bako 2 2,035 Apr-29-2020, 05:07 PM
Last Post: bako
  How to automate list separation. NOOB LobateScarp 18 5,640 Sep-24-2019, 07:28 PM
Last Post: LobateScarp
  Getting Cells from the Sheets "automate the boring stuff" Shafla 8 4,075 Sep-24-2019, 04:53 AM
Last Post: snippsat
  Help|CSV Writing on List with Inner Commas soothsayerpg 2 2,398 Jul-20-2019, 06:59 AM
Last Post: scidam

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020