Four ways to add elements to a List in Python

  • 2020-04-02 14:28:16
  • OfStack

List is a data type commonly used in Python. It is an ordered collection, in which the elements are always in the order they were originally defined (unless you sort them or otherwise modify them).

In Python, adding an element to a List can be done in the following four ways (append(),extend(),insert(), + +)

Append () appends a single element to the end of the List , only one parameter can be accepted. The parameter can be any data type. The appended element keeps the original structure type in the List.

If this element is a list, the list is appended as a whole, note the difference between append() and extend().


>>> list1=['a','b']
>>> list1.append('c')
>>> list1
['a', 'b', 'c']

Extend () adds each element in one list to the other , only one parameter is accepted; Extend () is equivalent to connecting list B to list A.


>>> list1
['a', 'b', 'c']
>>> list1.extend('d')
>>> list1
['a', 'b', 'c', 'd']

Insert () inserts an element into the list with two arguments (such as insert(1, "g")), The first parameter is the index point, where it is inserted, and the second parameter is the inserted element.


>>> list1
['a', 'b', 'c', 'd']
>>> list1.insert(1,'x')
>>> list1
['a', 'x', 'b', 'c', 'd']

4. Plus sign, add the two lists, and a new list object will be returned. Note the difference with the previous three. The previous three methods (append, extend, insert) add an element to the list. They do not return a value and directly modify the original data object. Note: adding the two lists requires the creation of a new list object, which consumes extra memory, especially if the list is large, try not to use "+" to add the list, and use the list's append() method if possible.


>>> list1
['a', 'x', 'b', 'c', 'd']
>>> list2=['y','z']
>>> list3=list1+list2
>>> list3
['a', 'x', 'b', 'c', 'd', 'y', 'z']


Related articles: