Several ways to add and delete elements in List in Python

Hi everyone, hello! I am a cheese who loves to touch fish ❤

1. Several ways to add elements to List in python

List is a commonly used data type in Python,

It is an ordered set,

That is, the elements in it always maintain the order of the initial definition

(unless you sort or otherwise modify them).

In Python, there are 4 methods
to add elements to List (append(), extend(), insert(), + plus sign).


1.append() Appends a single element to the end of the List,
accepts only one parameter, which
can be of any data type,
and 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().

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

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

>>> list1
['a', 'b', 'c']

>>>lis2=[]
>>> list2.extend([list1[0],list1[2]])
>>> list1
['a', 'c']

Note: The difference between extend and append is that extend can add multiple elements at the same time


3.insert() inserts an element into the list ,

But there are two parameters (such as insert(1,"g")),

The first parameter is the index point, which is the position to insert

The second parameter is the element to insert.

>>> list1
['a', 'b', 'c', 'd']
>>> list1.insert(1,'x')
>>> list1
['a', 'x', 'b', 'c', 'd']
~~~python
4.+ 加号,将两个list相加,会返回到一个新的list对象,注意与前三种的区别。前面三种方法(append, extend, insert)可对列表增加元素的操作,他们没有返回值,是直接修改了原数据对象。 注意:将两个list相加,需要创建新的list对象,从而需要消耗额外的内存,特别是当list较大时,尽量不要使用“+”来添加list,而应该尽可能使用List的append()方法。
~~~python
>>> list1
['a', 'x', 'b', 'c', 'd']
>>> list2=['y','z']
>>> list3=list1+list2
>>> list3
['a', 'x', 'b', 'c', 'd', 'y', 'z']

2. Several ways to delete elements from List in python

li = [1,2,3,4,5,6]

# 1.使用del删除对应下标的元素
del li[2]
# li = [1,2,4,5,6]

# 2.使用.pop()删除最后一个元素
li.pop()
# li = [1,2,4,5]

# 3.删除指定值的元素
li.remove(4)
# li = [1,2,5]

# 4.使用切片来删除
li = li[:-1]
# li = [1,2,3,4,5]
# !!!切忌使用这个方法,如果li被作为参数传入函数,
# 那么在函数内使用这种删除方法,将不会改变原list


li = [1,2,3,4,5,6]
def delete(li, index):
    li = li[:index] + li[index+1:]
delete(li, 3)
print(li)
# 会输出[1,2,3,4,5,6]

That's it for today's article~

See you in the next article (✿◡‿◡)

insert image description here

Guess you like

Origin blog.csdn.net/m0_74872863/article/details/130142438