To add an element or item to a python list, append() method is used. This method takes a single argument and adds this value to the end of list.
append() method accepts a single parameter and returns None.

append() syntax
Syntax of append() method is

list.append(element)

element is added to the end of the list. If the list already contains element, still the element is appended to the list and it becomes duplicate in the list.
Note that append() modifies the original list.
append() example
Below is an example of append() method in python list.

# create a list
l = [1,2,3]
print('Original List:',l)
# add an element
l.append(4);
# print list
print('List after appending:',l)
# add existing element
l.append(1)
# print list again
print('List after appending again:',l)

This produces following output

Original List: [1, 2, 3]
List after appending: [1, 2, 3, 4]
List after appending again: [1, 2, 3, 4, 1]
Append list to another list
Just like you can add a single element to a list with append(), it can also be used to add an entire list as an element to a list. Example,

# create a list
l1 = [1, 2, 3]
# create another list
l2 = ['a', 'b', 'c']
# add second list to first one
l1.append(l2)
print('Updated List:122`',l1)

This will add the second list, as it is, to the end of first list. This means that the last list element will be a list instead of a single element as evident from the below output.

Updated list: [1, 2, 3, [a, b, c]]

Notice the last element is enclosed between square brackets which means that it is a list. If you check the type of the last element using type() function, then you get <class 'list'>.

If you want all elements of the second list to be appended to the first list, then use extend() method of list.

Hit the clap if the article was useful.

0
Liked the article ? Spread the word...

Leave a Reply