Add content to list in Python

1. append() Appends a single element to the end of the List. It only accepts one parameter. All contents enclosed in quotation marks are characters or strings by default. Remember to delete the quotation marks when using other data types.

 

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

>>> a = ['a','b','c']
>>> B = ['1','2','3']
>>> a.append('B')
>>> a.append(B)
>>> a
['a', 'b', 'c', 'B','1','2','3']

>>> C = {'name':123}
>>> a.append(C)
>>> a
['a', 'b', 'c', {'name': 123}]

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

 

 

2. extend() adds each element in one list to another list, accepting only one parameter; extend() is equivalent to continuing list B to the end of list A.

 

>>> a = ['a','b','c']
>>> B = ['1','2','3']
>>> a.extend(B)
>>> a
['a', 'b', 'c', '1', '2', '3']
>>> a.extend('qwe')
>>> a
['a', 'b', 'c','q', 'w', 'e']

 

 

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, that is, the insertion position, and the second parameter is the insertion position Elements.

 

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

 

 

4. + plus sign, adding two lists will return a new list object (only limited to the list data format), pay attention to the difference with 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: 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() method as much as possible .

 

>>> a = ['a','b','c']
>>> B = ['1','2','3']
>>> C = {'name':123}
>>> d = a+b
>>> d
['a', 'b', 'c', '1', '2', '3']
>>> e = a+C
Traceback (most recent call last):
  File "<console>", line 1, in <module>
TypeError: can only concatenate list (not "dict") to list

 

 

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326776195&siteId=291194637