Python list of common methods of operation summary

  • 2020-04-02 14:34:11
  • OfStack

Common list object operation methods:

List. Append (x)

Adding an element to the end of the list is the same thing as a[len(a):] = [x].

List. The extend (L)

Adding all the elements in a given list to another list is equivalent to a[len(a):] = L.

List. The insert (I, x)

Inserts an element at the specified location. The first parameter is the index of the element to be inserted in front of it. For example, a.insert(0, x) will be inserted before the entire list, and a.insert(len(a), x) is equal to a.append(x).

List. Remove (x)

Deletes the first element in the list whose value is x. If there is no such element, an error is returned.

Pop ([I]) is list.

Deletes an element from the specified position in the list and returns it. If no index is specified, a.op () returns the last element. The element is then deleted from the list. (the square brackets around the I in the method indicate that the parameter is optional, rather than requiring you to enter a pair of square brackets, which you will often encounter in the Python library reference manual.)

List. The index (x)

Returns the index of the element in the list whose first value is x. An error is returned if there is no matching element.

List. The count (x)

Returns the number of times x appears in a linked list.

List. The sort ()

Sort the elements of a linked list in place.

List. The reverse ()

Invert the elements of the list in place.

Ex. :


>>> a = [66.25, 333, 333, 1, 1234.5]
>>> print a.count(333), a.count(66.25), a.count( ' x')
2 1 0
>>> a.insert(2, -1)
>>> a.append(333)
>>> a
[66.25, 333, -1, 333, 1, 1234.5, 333]
>>> a.index(333)
1
>>> a.remove(333)
>>> a.index(333)
2
>>> a
[66.25, -1, 333, 1, 1234.5, 333]
>>> a.reverse()
>>> a
[333, 1234.5, 1, 333, -1, 66.25]
>>> a.sort()
>>> a
[-1, 1, 66.25, 333, 333, 1234.5]


Related articles: