Skip to content
Home » Inserting Elements to Lists in Python

Inserting Elements to Lists in Python

Spread the love

You already know how to append elements at the end of a list. This is what you use the append method for. In this video you’ll learn how to insert elements at arbitrary positions in a list.

Here’s the video version of this article:

If you want to add elements at arbitrary indices, you can use the method insert(index, x), which inserts x at index:

>>> dates = [1994, 2001, 2005, 2014]
>>> dates.insert(2, 2003)  # inserts 2003 at index 2
>>> dates
[1994, 2001, 2003, 2005, 2014]

You can insert an element at the end, which is what you also achieve using the append function. You can do it like so:

>>> dates.insert(len(dates), 2016)
>>> dates
[1994, 2001, 2003, 2005, 2014, 2016]

or you can use the new index the object will be at:

>>> dates.insert(6, 2018)
>>> dates
[1994, 2001, 2003, 2005, 2014, 2016, 2018]

You can even use any index greater than the last one:

>>> dates.insert(50, 2019)
>>> dates
[1994, 2001, 2003, 2005, 2014, 2016, 2018, 2019]

The index will be set to the next available index anyway. So, even though we tried to insert the new element at index 50, it will be at index 7 in this case:

>>> dates.index(2019)
7

Your Panda3D Magazine

Make Awesome Games and Other 3D Apps

with Panda3D and Blender using Python.

Cool stuff, easy to follow articles.

Get the magazine here (PDF).

Python Jumpstart Course

Learn the basics of Python, including OOP.

with lots of exercises, easy to follow

The course is available on Udemy.

Blender Jumpstart Course

Learn the basics of 3D modeling in Blender.

step-by-step, easy to follow, visually rich

The course is available on Udemy and on Skillshare.


Spread the love
Tags:

Leave a Reply