Python : How to Add an Element in List ? | append() vs extend()

A collection is an ordered list of values. There could be various types of values. A list is a mutable container. This means that existing ones can be added to, deleted from, or changed.

The Python list represents the mathematical concept of a finite sequence. List values are referred to as list items or list elements. The same value may appear multiple times in a list. Each event is regarded as a distinct element.

Given a list, the task is to add the elements to the givenlist using append and extend methods

Adding element to the list

We can add elements to list by several methods some of them are:

Method #1:Using append()

To add elements to the List, use the built-in append() function. The append() method can only add one element to a list at a time; loops are used to add multiple elements to a list using the append() method. Tuples can be added to the List using the append method because they are immutable. Lists, unlike Sets, can be appended to another list using the append() method.

Below is the implementation:

# given list
givenlist = ['hello', 'this', 'is', 'BtechGeeks']
# adding element to the givenlist using append() function
givenlist.append('Python')
# print the list
print(givenlist)

Output:

['hello', 'this', 'is', 'BtechGeeks', 'Python']

Method #2:Using append() function to add multiple elements

Because a list can contain various types of elements, we can pass another list object as a parameter in append ()

Below is the implementation:

# given list
givenlist = ['hello', 'this', 'is', 'BtechGeeks']
# given elementslist which should be added
elementslist = ['python', 'code']
# adding elementslist to the givenlist using append() function
givenlist.append(elementslist)
# print the list
print(givenlist)

Output:

['hello', 'this', 'is', 'BtechGeeks', ['python', 'code']]

Method #3:Using extend() function

Other than the append() and insert() methods for adding elements, there is extend(), which is used at the end of the list to add multiple elements at once.

Append() and extend() can only add elements at the end of a list.

Below is the implementation:

# given list
givenlist = ['hello', 'this', 'is', 'BtechGeeks']
# given elementslist which should be added
elementslist = ['python', 'code']
# adding elementslist to the givenlist using append() function
givenlist.extend(elementslist)
# print the list
print(givenlist)

Output:

['hello', 'this', 'is', 'BtechGeeks', 'python', 'code']

append() vs extend()

list.append(item) treats the parameter item as an individual object and appends it to the end of the list. Even if the given item is already in another list, it will be added to the end of the list as an individual object.

list.extend(item) treats parameter item as a new list and adds all of the list’s individual elements to the current list.
Related Programs: