0

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" enter image description here

1 Answer 1

1

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")
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks so much. I got clarity now.
@yuppiesam you can think about accepting the answer so ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.