Home > Article > Backend Development > 4 ways to add elements to List in Python_python
This article mainly introduces the sharing of 4 methods to add elements to List in Python. This article explains the 4 methods of append(), extend(), insert(), plus sign, etc., and gives operation examples. Friends in need can refer to
List is a commonly used data type in Python. It is an ordered collection, that is, the elements in it always maintain the initial defined order (unless you sort them or otherwise modify them) operate).
In Python, there are four methods to add elements to List (append(), extend(), insert(), + plus sign)
1. append () Append a single element to the end of the List. It only accepts one parameter. The parameter can be any data type. The appended element maintains the original structure type in the List.
If this element is a list, then the list will be appended as a whole. Pay attention to the difference between append() and extend().
Copy code The code is as follows:
>>> 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.
Copy code The code is as follows:
>>> list1
['a', 'b', 'c']
>>> list1.extend('d')
>>> list1
['a', 'b', 'c' , 'd']
3. insert() inserts an element into the list, but its parameters have two (such as insert(1,”g”)), The first parameter is the index point, which is the inserted position, and the second parameter is the inserted element.
Copy code The code is as follows:
>>> list1
['a', 'b', 'c', 'd']
>>> list1.insert(1,'x')
>>> list1
['a', ' x', 'b', 'c', 'd']
4. + plus sign, adding two lists will return a new list object. Note Differences 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. Note: Adding two lists requires creating a new list object, which consumes additional memory. Especially when the list is large, try not to use "+" to add the list. Instead, use List's append( )method.
Copy code The code is as follows:
>>> list1
['a', 'x', 'b', 'c', 'd']
>>> list2=['y','z']
>>> list3=list1+list2
>>> list3
['a', 'x', 'b', 'c', 'd', 'y', 'z']
Related recommendations:
How to achieve mutual conversion from str to list in Python
##
The above is the detailed content of 4 ways to add elements to List in Python_python. For more information, please follow other related articles on the PHP Chinese website!