Common methods of python3 list list

#python3 list common methods of list

li = [1,2,3]

# append
li.append('4') #append method, append an element at the end, only one can be added at a time, the return value of the method is None

help(li.append) # View help documentation
'''
append(...) method of builtins.list instance
    L.append(object) -> None -- append object to end
'''


# clera clears the entire list, use with caution

li.clear()
help(li.clear)
'''
clear(...) method of builtins.list instance
    L.clear() -> None -- remove all items from L
'''
# copy creates a new object, while = refers to a common address

li2=li.copy()

li3=[1,2]
li4=li3
id(li3)
id(li4)

'''
>>> id(li3)
2737674012104
>>> id(li4)
2737674012104
'''
li3[1]=1
print(li4)
#[1, 1]
#The same reference address, one object changes, the other object also changes



#count() count, returns the number of times the element appears in the list

li3.count(3)


#extend pass in an iterable object

li3.extend('str')
print(li3)
#[1, 1, 's', 't', 'r']

#It adds iterative objects in turn



# index returns the element subscript with two optional parameters, which are the start position and the end position. Note that the left is closed and the right is open.

li3.index('s')

li3.index('s',2,3)

# If not found, an error will be reported

#insert specifies inserting a certain position

li3.insert(0,1) # Insert a 1 at the position of index 0 to make up for the defect that append can only be added at the end

# pop does not select the parameter to pop the last element by default, and the return value is the popped element

li3.pop()

'''
[1, 1, 's', 't', 'r']
>>> li3
[1, 1, 1, 's', 't']
'''
li3.pop(3) #Remove the element at the specified index

# remove # remove the first matching element in the list
li3.remove('s')



# reverse() reverse the list

li3.reverse()

# sort() sort
li3.sort(key=str) #means to sort all the elements according to the string according to the ascii code










Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325801185&siteId=291194637