
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Append Objects in a List in Python
List is one of the most commonly used data structures provided by python. List is a data structure in Python that is mutable and has an ordered sequence of elements.
In this article, we will discuss how to add objects to a list and the different ways to add objects, such as append(), insert(), and extend() methods, in Python.
Using append() method
In this method, we use append() to add objects to a list. The append() method adds a new element to the end of a list that already exists.
Example 1
In this example, we used the append() method to add objects to a list. Here, we have added another name to the list of names(names_list).
names_list = ["Meredith", "Levi", "Wright", "Franklin"] names_list.append("Kristen") print(names_list)
Output
After running the program, you will get this result:
['Meredith', 'Levi', 'Wright', 'Franklin', 'Kristen']
Example 2
Following is another example to append the element to a list -
numbers_list = [2, 5, 46, 78, 45] numbers_list.append(54) print ('The list with the number appended is:',numbers_list)
Output
This output will be displayed when the program runs:
The list with the number appended is: [2, 5, 46, 78, 45, 54]
Using the insert() method
In this method, we use insert() to add objects to a list. The insert() method adds a new element at the specified position of the list.
Example
In this example, to add an item at the 2nd position of the list, we used the insert() method.
lst = ["Bat", "Ball"] lst.insert(2,"Wicket") print(lst)
Output
The output of the above program is as follows.
['Bat', 'Ball', 'Wicket']
Using the extend() method
In this method, we will look at extend() method to combine all elements from one list into another by concatenating (adding) them together.
Example
In the following code, we will concatenate two lists using the extend() method.
names_list = ["Meredith", "Levi"] othernames_list = [ "Franklin", "Wright"] names_list.extend(othernames_list) print(names_list)
Output
You will see this result after executing the program:
['Meredith', 'Levi', 'Franklin', 'Wright']