Which method is used to add one item in a list in Python?

Methods to add elements to List in Python

There are four methods to add elements to a List in Python.

  1. append(): append the object to the end of the list.
  2. insert(): inserts the object before the given index.
  3. extend(): extends the list by appending elements from the iterable.
  4. List Concatenation: We can use + operator to concatenate multiple lists and create a new list.

Python lists

last modified December 15, 2021

In this part of the Python programming tutorial, we cover Python lists in more detail.

Python's .append(): Add Items to Your Lists in Place

by Leodanis Pozo Ramos basics python
Mark as Completed
Tweet Share Email

Table of Contents

Remove ads

Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Building Lists With Python's .append()

Adding items to a list is a fairly common task in Python, so the language provides a bunch of methods and operators that can help you out with this operation. One of those methods is .append(). With .append(), you can add items to the end of an existing list object. You can also use .append() in a for loop to populate lists programmatically.

In this tutorial, you’ll learn how to:

  • Work with .append()
  • Populate lists using .append() and a for loop
  • Replace .append() with list comprehensions
  • Work with .append() in array.array() and collections.deque()

You’ll also code some examples of how to use .append() in practice. With this knowledge, you’ll be able to effectively use .append() in your programs.

Free Download: Get a sample chapter from Python Basics: A Practical Introduction to Python 3 to see how you can go from beginner to intermediate in Python with a complete curriculum, up-to-date for Python 3.8.

Using list methods to add data: append() vs. extend()

The .append() method increases the length of the list by one, so if you want to add only one element to the list, you can use this method.

x = [1, 2, 3] x.append(4) x [1, 2, 3, 4]

The .extend() method increases the length of the list by the number of elements that are provided to the method, so if you want to add multiple elements to the list, you can use this method.

x = [1, 2, 3] x.extend([4, 5]) x [1, 2, 3, 4, 5]

Interactive example of the append() and extend() methods

We start with the list names:

names = ['Apple Inc', 'Coca-Cola', 'Walmart'] # Append a name to the list names names.append('Amazon.com') print(names)

When we run the above code, it produces the following result:

names = ['Apple Inc', 'Coca-Cola', 'Walmart', 'Amazon.com']

We can then add two additional elements to the list names using extend() and the more_elements list.

# Extend list names more_elements = ['DowDuPont', 'Alphabet Inc'] names.extend(more_elements) print(names)

When we run the above code, it produces the following result:

['Apple Inc', 'Coca-Cola', 'Walmart', 'Amazon.com', 'DowDuPont', 'Alphabet Inc']

Try it for yourself.

To learn more about list methods and functions, please see this video from our course Introduction to Python for Finance.

This content is taken from DataCamp’s Introduction to Python for Finance course by Adina Howe.

Add an item to a list in Python (append, extend, insert)

Posted: 2019-05-29 / Modified: 2021-04-06 / Tags: Python, List
Tweet

In Python, use list methods append(), extend(), and insert() to add items (elements) to a list or combine other lists. You can also use the + operator to combine lists, or use slices to insert items at specific positions.

  • Add an item to the end: append()
  • Combine lists: extend(), + operator
  • Insert an item at specified index: insert()
  • Add another list or tuple at specified index: slice
Sponsored Link

Methods:

Many methods exist in Python to modify the list. Some common methods to add and remove data in the list are mentioned here.

insert (index,item): This method is used to insert any item in the particular index of the list and right shift the list items.

append (item): This method is used to add new element at the end of the list.

extend (anotherList): The items of one list can be inserted at the end of another list by using this method.

remove (item): This method is used to remove particular item from the list.

pop (index): The method is used to remove item from the list based on index value.

del(): This method is used to remove the particular item of the list or slice the list.

clear(): This method is used to remove all items of a list

Add items into the list:

Different ways to add items in Python list are shown in this part of the tutorial.

Example 1: Insert item using insert() method

Create a python file with the following script to see the use of insert() method. A new item will be inserted in the third position of the list and the other items will be shifted right after running the script.

# Declare list
listdata = [89, 56, 90, 34, 89, 12]

# Insert data in the 2nd position
listdata.insert(2, 23)

# Displaying list after inserting
print("The list elements are")

for i in range(0, len(listdata)):
print(listdata[i])

Output:

The following output will appear after running the script.

Example 2: Insert item using append() method

Create a python file with the following script to see the use of append() method. It is mentioned before that append() method inserts data at the end of the list. So, ‘Toshiba’ will be inserted at the end of listdata after running the script.

# Define the list
listdata = ["Dell", "HP", "Leveno", "Asus"]

# Insert data using append method
listdata.append("Toshiba")

# Display the list after insert
print("The list elements are")

for i in range(0, len(listdata)):
print(listdata[i])

Output:

The following output will appear after running the script.

Example 3: Insert item using extend() method

Create a python file with the following script to see the use of extend() method. Here, two lists are declared in the script which are combined together by using extend() method. The items of the second list will be added at the end of the first list.

# initializing the first list
list1 = ['html', 'CSS', 'JavaScript', 'JQuery']

# initializing the second list
list2 = ['PHP', 'Laravel', 'CodeIgniter']

# Combine both lists using extend() method
list1.extend(list2)

# Display the list after combing
print ("The list elements are :")

for i in range(0, len(list1)):
print(list1[i])

Output:

The following output will appear after running the script.

Python List Refresher

Python lists can store zero or more items of a specific data type, such as strings, JSON objects, or numbers. For example, you can use a list to store a list of names or addresses. Lists are mutable. This means you can change their contents.

To create a new list in Python, you need to separate a list of values with commas and enclose it in square brackets []. Let’s create a list in Python, using this code:

toy_animals = ["Shark", "Dragon", "Bear", "Cat", "Giraffe"]

When we print out our list to the console, we can see the list that we’ve defined:

print(toy_animals)

Output:

["Shark", "Dragon", "Bear", "Cat", "Giraffe"]

Each item on our list has an index number, which can be used to reference an individual list item. These index numbers start with the value and increase for each item in a list. For our above toy_animals list, index numbers are assigned like this:

81% of participants stated they felt more confident about their tech job prospects after attending a bootcamp. Get matched to a bootcamp today.

Find Your Bootcamp Match

The average bootcamp grad spent less than six months in career transition, from starting a bootcamp to finding their first job.

Start your career switch today
» MORE: JavaScript String Contains: Step-By-Step Guide
“Shark”“Dragon”“Bear”“Cat”“Giraffe”
1234

The first item on our list Shark has the value 0. The last item Giraffe has the value 4. We can use these index numbers to access and manipulate our list. So, if we want to access the element with the index number 1, we can use the following code:

print(toy_animals[1])

Output:

"Dragon"

Lists are mutable, which means that you can add and remove items to an existing list. Now that we’ve explored the basics of lists and list indexing in Python, we can start using the append() and insert() methods.

Video liên quan

Postingan terbaru

LIHAT SEMUA