[python] 4 ways to add elements to List

Hits: 0

In Python, there are four ways to add elements to a List: append(), extend(), insert(), plus sign +

[1] append() Appends a single element to the end of the List. It only accepts one parameter. The parameter can be any data type. The added element maintains the original structure type in the List.
If this element is a list, the list will be appended as a whole, pay attention to the difference between append() and [extend] and [extend] ().

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

[2] extend() adds each element in one list to another list, accepting only one parameter; extend() is equivalent to connecting list B to list A.

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

[3] [insert] (i,val) inserts an element val into the i index of the list, the first parameter is the index, that is, the insertion position, 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 +, adding two lists will return to a new list object, pay attention to the difference from the first three. The first three methods (append, extend, insert) can add elements to the list. They have no return value and directly modify the original data object. To add two lists, a new list object needs to be created, which requires additional memory consumption. Especially when the list is large, try not to use “+” to add the list, but use the append() of the List as much as possible. method.

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

You may also like...

Leave a Reply

Your email address will not be published.