Get the App
SLTechnology News&Howtos  ›  Database  › 

Common methods of listing python

Shulou Source: shulou.com Published: 2022-06-01 06:23:51 10月02日 Update

For more information on how to use the list and API, please refer to the Python documentation: http://docs.python.org/2/library/functions.html

Append: used to append new objects to the end of the list:

# append function

Lst = [1pm 2pm 3]

Lst.append (4)

# output: [1, 2, 3, 4]

Print lst

Copy the code

Count: used to count the number of times an element appears in the list:

# count function

Temp_str = ['to','be','not','to','be']

# output: 2

Print temp_str.count ('to')

Extend: you can append multiple values from another sequence at the end of the list at once. Unlike the join operation, the extend method modifies the extended sequence (the sequence that calls the extend method), while the original join operation returns a completely new list.

# extend function

A = [1pm 2pm 3]

B = [4, 5, 5, 6]

A.extend (b)

# output: [1,2,3,4,5,6]

Print a

# output: [1, 2, 3, 4, 5, 6, 7, 8,9]

Print a + [7, 8, 8, 9]

# output: [1,2,3,4,5,6]

Print a

Index: the index position used to find the first match of a value from the list

# index function

Knights = ['we','are','the','knights','who','say','ni']

# output: 4

Print knights.index ('who')

# throw an exception: ValueError: 'me' is not in list

Print knights.index ('me')

Insert: used to insert objects into the list

# insert function

Numbers = [1, 2, 3, 5, 6]

Numbers.insert (3)

# output: [1, 2, 3, 'four', 5, 6]

Print numbers

Pop: removes an element from the list (the last one by default) and returns the value of that element. Through the pop method, we can implement a common data structure-LIFO (LIFO).

# pop function

X = [1pm 2pm 3]

X.pop ()

# output: [1,2]

Print x

Y = x.pop (0)

# output: [2]

Print x

# output: 1

Print y

Remove: removes the first occurrence of a value in the list

# remove function

X = ['to','be','not','to','be']

X.remove ('to')

# output: ['be',' not', 'to',' be']

Print x

# removing elements that are not in the list will throw an exception

X.remove ('too')

Reverse: store the elements in the list in reverse

# reverse function

X = [1pm 2pm 3]

X.reverse ()

# output: [3, 2, 1]

Print x

Sort: sorts the list. Note: the sort function does not return a value (None), it acts on the source sequence. You can get a sorted copy of the list through the sorted function.

# sort function

X = [3, 1, 2, 7, 6, 9, 5, 4, 8]

Y = x [:]

Z = x

Y.sort ()

# output: [3, 1, 2, 7, 6, 9, 5, 4, 8]

Print x

# output: [1, 2, 3, 4, 5, 6, 7, 8,9]

Print y

# output: [3, 1, 2, 7, 6, 9, 5, 4, 8]

Print z

Tags: Output function element method sequence object end sort different original one-time code location function usage brand new copy can pass backward multiple Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Information Redmi NVidia OPPO Reno MariaDB