Adding List Items in Python: Appending and Inserting Elements

thumb_up 1  ·  sell Appending and inserting elements in Python lists, Adding items to a Python list, Python list item addition

There are two methods of the list class, append() and insert(), that are used to add items to an existing list.

Example 1

The append() method adds the item at the end of an existing list.

 
list1 = ["a", "b", "c", "d"] print ("Original list: ", list1) list1.append('e') print ("List after appending: ", list1)

Output

It will produce the following output −

Original list: ['a', 'b', 'c', 'd']
List after appending: ['a', 'b', 'c', 'd', 'e']

Example 2

The insert() method inserts the item at a specified index in the list.

 
list1 = ["Rohan", "Physics", 21, 69.75] print ("Original list ", list1) list1.insert(2, 'Chemistry') print ("List after appending: ", list1) list1.insert(-1, 'Pass') print ("List after appending: ", list1)

Output

It will produce the following output −

Original list ['Rohan', 'Physics', 21, 69.75]
List after appending: ['Rohan', 'Physics', 'Chemistry', 21, 69.75]
List after appending: ['Rohan', 'Physics', 'Chemistry', 21, 'Pass', 69.75]

We know that "-1" index points to the last item in the list. However, note that, the item at index "-1" in the original list is 69.75. This index is not refreshed after appending 'chemistry'. Hence, 'Pass' is not inserted at the updated index "-1", but the previous index "-1".

 

 

 

The End! should you have any inquiries, we encourage you to reach out to the Vercaa Support Center without hesitation.

Was this answer helpful?

Related Articles

description

Exploring Python's Key Characteristic

Python is a feature rich high-level, interpreted, interactive and object-oriented scripting language. This tutorial will list down some of…

arrow_forward
description

Comparing Python and C++

Both Python and C++ are among the most popular programming languages. Both of them have their advantages and disadvantages. In this…

arrow_forward
description

Creating a Python Hello World Program

This tutorial will teach you how to write a simple Hello World program using Python Programming language. This program will make use of…

arrow_forward
description

Python's Versatile Application Domains

Python is a general-purpose programming language. It is suitable for development of wide range of software applications. Over last few…

arrow_forward
description

Understanding the Python Interpreter

Python is an interpreter-based language. In a Linux system, Python's executable is installed in /usr/bin/ directory. For Windows, the…

arrow_forward
arrow_back « Back