Reputation: 1
i am trying my hands on some python list practice question. i tried to insert a new name mike at index "-1" but upon printing output to the screen i noticed it defaulted to another position (index (-2))in the dinner list.
dinner = ['yemi', 'bimpe', 'kola', 'kunle', 'bola', 'shola', 'ola']
invite = f"{dinner[0].title()}, would you be available to attend our dinner party?"
print(invite)
invite = f"{dinner[-1].title()}, would you be available to attend our dinner party?"
print(invite)
invite = f"{dinner[-3].title()}, would you be available to attend our dinner party?"
print(invite)
invite = f"{dinner[3].title()}, would you be available to attend our dinner party?"
print(invite)
invite = f"{dinner[1].title()}, would you be available to attend our dinner party?"
print(invite)
not_coming = f"{dinner[0].title()} said she can't make the dinner party tonight and has to be swapped with {dinner[1].title()}"
print(not_coming)
not_coming = f"{dinner[-1].title()} said she can't make the dinner party tonight and has to be swapped with {dinner[-2].title()}"
print(not_coming)
dinner.insert(0, "kingsley")
print(dinner)
dinner.insert(-1, "mike")
print(dinner)
why is this so?
the list name is "dinner"
Upvotes: 0
Views: 50
Reputation: 54148
The documentation of list.insert
states
Insert an item at a given position. The first argument is the index of the element before which to insert
So if you use the index -1
, it'll insert just before the last one
To insert last use either one of these
dinner.insert(len(dinner), "mike")
dinner.append("mike")
Upvotes: 1