FAQ: Working with Lists in Python - Adding by Index: Insert

This community-built FAQ covers the “Adding by Index: Insert” exercise from the lesson “Working with Lists in Python”.

Paths and Courses
This exercise can be found in the following Codecademy content:

Data Scientist
Analyze Data with Python
Computer Science
Analyze Financial Data with Python
Build Chatbots with Python
Build Python Web Apps with Flask
Data Analyst

Learn Python 3
CS101 Livestream Series

FAQs on the exercise Adding by Index: Insert

There are currently no frequently asked questions associated with this exercise – that’s where you come in! You can contribute to this section by offering your own questions, answers, or clarifications on this exercise. Ask or answer a question by clicking reply (reply) below.

If you’ve had an “aha” moment about the concepts, formatting, syntax, or anything else with this exercise, consider sharing those insights! Teaching others and answering their questions is one of the best ways to learn and stay sharp.

Join the Discussion. Help a fellow learner on their journey.

Ask or answer a question about this exercise by clicking reply (reply) below!
You can also find further discussion and get answers to your questions over in Language Help.

Agree with a comment or answer? Like (like) to up-vote the contribution!

Need broader help or resources? Head to Language Help and Tips and Resources. If you are wanting feedback or inspiration for a project, check out Projects.

Looking for motivation to keep learning? Join our wider discussions in Community

Learn more about how to use this guide.

Found a bug? Report it online, or post in Bug Reporting

Have a question about your account or billing? Reach out to our customer support team!

None of the above? Find out where to ask other questions here!

#Which of the following lines of code will insert “Gus” as the middle element of the list friends?

friends = [“Annabelle”, “Greg”, “Katya”, “Sol”]

1, insert(friends, 2, “Gus”)

2, friends.insert(-2, “Gus”)

3, friends.insert(1, “Gus”)

4, friends.insert(-3, “Gus”)

Why the answer is not 4?

2, friends.insert(-2, “Gus”)
print(friends)
[“Annabelle”, “Greg”, “Gus”, “Katya”, “Sol”]

4, friends.insert(-3, “Gus”)
print(friends)
[“Annabelle”, “Gus”, “Greg”, “Katya”, “Sol”]

2 Likes

If you’re posting code to the forums please see- How do I format code in my posts? as it makes it much easier for everyone else to read.

As you can see from your printed output, "Gus" is not the middle element of the resulting list when using an index of -3. Since you included the second example too is that the one you meant?

For an item with 4 elements the indices listed below are equivalent when using lst[index]-

->  0,  1,  2,  3
-> -1, -2, -3, -4

So friends.insert(2, "Gus") or friends.insert(-2, "Gus") would create equivalent objects in this example-

friends = ["Annabelle", "Greg", "Katya", "Sol"]
lst1 = friends.insert(2, "Gus")
friends = ["Annabelle", "Greg", "Katya", "Sol"]
lst2 = friends.insert(-2, "Gus")
print(lst1 == lst2)
Out: True
2 Likes

Hi tgrtim,
Thank you for replying! I am a new learner with 0 experience with anything related to computer program. :joy: I will take a look of the format.

In this question, I thought the correct answer is friends.insert(-3, “Gus”).

In the lecture Accessing List Elements: Negative Index
I learned that
pancake_recipe = [“eggs”, “flour”, “butter”, “milk”, “sugar”, “love”]

Element Index
eggs -6
flower -5
butter -4
milk -3
sugar -2
love -1

Following this example, “Sol” is -1, “Katay” is -2, I want to add a new name “Gus” before “Katya”, should I add it to -3? I am still confused.

Thank you again for taking time read my post and replying!

3 Likes

Whoops, sorry. Wrote those indices backwards, it should’ve been-

->  0,  1,  2,  3
-> -4, -3, -2, -1

and… I messed up the code afterwards, it’s not my day. Sorry about that :dizzy_face:

friends1 = ["Annabelle", "Greg", "Katya", "Sol"]
friends1.insert(2, "Gus")
friends2 = ["Annabelle", "Greg", "Katya", "Sol"]
friends2.insert(-2, "Gus")
print(friends1, "\n", friends2)
print(friends1 == friends2)

Now it’s a little more obvious about 2 and -2 lining up to provide an index to the same element for the example with 4 elements.

The docs specify how insert works, see- 5. Data Structures — Python 3.9.5 documentation It insert the element at that exact index (so you’d move the current element and further elements one to the right).

As you said, “Katay” is the element found at friends[-2] (we could also address the same element with friends[2] in this case). If we insert “Gus” at this exact it moves the current element and any elements to the right one step further to the right.

                               friends[2]
                                   |
friends = ["Annabelle", "Greg", "Katya", "Sol"]
friends.insert("Gus", 2)

                            "Gus" goes here
                                   |
friends = ["Annabelle", "Greg",         ,  "Katya", "Sol"]
                                              |
                          The previous element at that location,
                        and the elements to the right, shift right

When you’re trying to get your head around a concept like this I think actually testing it and seeing the result helps no end. If you trial the code I added above (with .insert and print) it should show this but feel free to play around with it and keep printing the outcome so you know for sure. There’s no need for programming to be a black box :slightly_smiling_face:.

3 Likes

Thank you so much! I have tired the code you provided. The test shows friends1.insert(2, “Gus”) and friends2.insert(-2, “Gus”) have same result.

The picture showing how insert( ) moves the previous element and the element to the right shift one space to the right helps a lot! It gives me a clear thinking path. Now I know why friends.insert(-3, “Gus”) output [“Annabelle”, “Gus”, “Greg”, “Katya”, “Sol”]. Since I want to add “Gus” to the position “Greg” stands, this action moves “Greg” and any elements to the right of “Gerg” shift one space to the right. “Gus” is ends up at [-4].

Thank your for you time! And hope you have a wonderful day! :smiley:

4 Likes

Hi I am really new to this just 10% into my computer science course have a small question about
below insert code; when I inserted the Pineapple it would not print until I moved the print code to below the insert code is this how it works?
front_display_list = [“Mango”, “Filet Mignon”, “Chocolate Milk”]

Your code below:

front_display_list.insert(0, “Pineapple”)
print(front_display_list)

If I understand you correctly then yes that’s exactly how it works. Your commands are run in order. If you used print before the .insert() then you’d be printing the list as it is at that moment. Try printing before and after if you wanted to see the difference.

1 Like

I understand the point of .index(), though I think I’m missing something. A couple of exercises ahead of here is a project where you need to help a pizza place work out a bunch of stuff, and one point that I had trouble is a hint told me to use the .index() to add into the 2D list, the element [2.5, peppers]. If I attempt to type:

pizza_and_prices = pizza_and_prices = [[2.00, "pepperoni"], [6.00, "pineapple"], [1.00, "cheese"], [3.00, "sausage"], [2.00, "olives"], [7.00, "anchovies"], [2.00, "mushrooms"]] pizza_and_prices.insert(2.5, "peppers") print(pizza_and_prices)

into the code, it throws me a typeerror of “Integer Argument Expected, Got Float”

Are floats not allowed to be used in an .insert(),?

Also, this is editted down, as I’m brand new to this and I’m sure the full page is a mess, however the coding above throws an identical error, so I assume the answer can be found with it.

Yes your code snippet makes sense, ta. I think you meant .insert instead of .index here but apologies if that’s not the case. The .insert() method of a list object takes two arguments, an object to insert and the index at which to insert it- https://docs.python.org/3/library/stdtypes.html#mutable-sequence-types

So the issue you have in your example is that you are supplying a supposed index of 2.5 and lists only support integer indicies. If you want to insert [2.5, "peppers"] as a single element you’d need to pass the correct index and pass that entire object. Here’s a closer example of how that might look-

[].insert(0, ["a", "b"])

I think there might be a dev comment on this particular project you mention, it may be worth reading to see if it is relevant-

1 Like

When I was doing the same exercise estebandelmuerte9016 was doing I ran into an issue I wasn’t expecting with .insert()

Even though I know in the exercise one is supposed to insert Peppers in the correct order in the list, I was trying to add it as the last element with -1, however it added it as the second to last element and it makes sense now after reading the explanation tgrtim gave hollyd12. However, I was left wondering, how does one add an element to last in a list with .insert() or must we use .append() for this only?

1 Like

I think it would be better practice to use .append unless there’s a specific reason the use of indexing is important. The docs mention the following is valid though (using len itself isn’t the important part, just the integer it returns)-

a.insert(len(a), x) is equivalent to a.append(x)

From: https://docs.python.org/3/tutorial/datastructures.html#more-on-lists

It’s a new one for me but I just noted you can actually use .insert with an index beyond the length of the list and what’s more you can do the same for before the start of the list-

a = [1, 2, 3,] print(a) # insert before millionth index a.insert(999_999, 4) print(a) # inserts before start a.insert(-100, 5) print(a)

I always assumed it had bounds checking but it doesn’t. The value is used simply for what element should be before the insertion and I suppose you can think of it as being simply added before the closest match.

2 Likes

Wow, mate, this is impressive! Thank you so much for your answer! I definitely should get comfortable reading the documentation. Right now I find it to be so daunting and intimidating, but I guess I have to start getting used to it.

Same here, I had assumed that one could only input values within the index range of the list, it is definitely good to know that we can go way over. :open_mouth:

Also, I didn’t know that “_” is used as a replacement for comma in values over 999, so that’s something new as well. I guess it makes sense as commas are used to separate attributes/arguments in Python.

Many thank you! :blush:

1 Like

Aye, even navigating the docs is a skill in itself, much like “google-fu” and it’s repetition as much as study that helps. Added a few links I keep under the Python header that at least make a nice start (roughly the order of usefulness/complexity for me)-

The over the limits for .insert is very much new to me too and it’s not even mentioned in the docs, I just tried it to see what happens; genuinely surprised me.

As for the the _ as a numerical significance separtor that’s “relatively” new PEP 515 -- Underscores in Numeric Literals | Python.org (python3.6) but several languages have, or seem to be, introducing, the same (not always the same character) since it’s very human friendly so keep an eye out if you’re using something other than Python.

2 Likes

4 posts were split to a new topic: How we can round off a float to a give value?

Hi!

Having a bit of trouble understanding the insert() logic.

“Jiho would like to put "Pineapple" in the front of the list so it is the first item customers see in the display window.”
" Note : For this list, the front will be the element at index 0"

If an element is always added to the right of the index, how is this an exception? Shouldn’t we start with something <0 as 0 is the index for the first item and therefore pineapple would be added to the right of that? I understand that we can’t start with -1 since that would append the last item but 0 doesn’t seem to make sense to me since the list starts at 0.


front_display_list = [“Mango”, “Filet Mignon”, “Chocolate Milk”]
print(front_display_list)

front_display_list.insert(0, “Pineapple”)

print(front_display_list)


Where is it stated that the above happens?

The text of the exercise mentions:

When we insert an element into a list, all elements from the specified index and up to the last index are shifted one index to the right. This does not apply to inserting an element to the very end of a list as it will simply add an additional index and no other elements will need to shift.

In the code you posted,

front_display_list.insert(0, "Pineapple")

will insert “Pineapple” at index 0. Before the insert, index 0 was occupied by “Mango”. When we insert at a certain index, then the existing element at that index (and consequently all the elements after the existing element) are shifted one index to the right.

When we insert an element at a certain index, then the inserted element will be placed at that index. But, two elements can’t have the same index, so the element which previously occupied the index has to be moved to another index. The choice is: should the existing element be pushed to the right or to the left? The creator of the Python language decided to shift the elements to the right.

took me a while for that, was stuck here thanks