course content

Course Content

Python Data Structures

Insert() MethodInsert() Method

What if we want to add an item not at the end of the list, but at a specific position? For this purpose, we use the insert() method. Let's take a list called states as an example:

This list contains six items:

StatementValue
states[0] 'Washington'
states[1]'Florida'
states[2]'Georgia'
states[3]'California'
states[4]'New Mexico'
states[5]'Colorado'

For instance, if we want to insert 'Hawaii' at the beginning of the list, we would:

After this, 'Hawaii' takes the 0 index. It’s now at the top, and the rest of the items have shifted down. So, we now have 7 items:

StatementValue
states[0]'Hawaii'
states[1]'Washington'
states[2]'Florida'
states[3]'Georgia'
states[4]'California'
states[5]'New Mexico'
states[6]'Colorado'

Let’s say we want 'New York' right before 'Georgia'. Since Georgia is at index 3, we’ll give that index to New York.

Here’s how:

Previously, 'Georgia' was at index 3. Now 'New York' occupies that spot. Georgia and all items following it have moved down:

StatementValue
states[0]'Hawaii'
states[1]'Washington'
states[2]'Florida'
states[3]'New York'
states[4]'Georgia'
states[5]'California'
states[6]'New Mexico'
states[7]'Colorado'

Note

With the insert() function, you can add only one item at once.

Task

You have this list:

list_1 = ['ABBA', 'Aerosmith', 'The Animals', 'The Kinks']

You should modify it to:

list_1 = ['Kraftwerk', 'ABBA', 'Aerosmith', 'The Animals', 'New Order', 'The Kinks', 'The Orioles']

If you’re unsure about the indices for inserting items, refer to the hints. Only use positive indexing. Insert 'Kraftwerk' first, 'New Order' second, and 'The Orioles' last.

Everything was clear?

Section 1. Chapter 8
toggle bottom row