Python3 List pop() Method

Python3 列表Python3 Lists


Description

The pop() function is used to remove an element from a list (the last element by default) and return the value of that element.

Syntax

Syntax for the pop() method:

list.pop([index=-1])

Parameters

  • index -- Optional parameter, the index value of the list element to be removed. It cannot exceed the total length of the list. The default is index=-1, which removes the last list value.

Return Value

This method returns the element object removed from the list.

Example

The following example demonstrates how to use the pop() function:

Example

#!/usr/bin/python3

list1 = ['Google', 'Example', 'Taobao']
list1.pop()
print ("The list is now : ", list1)
list1.pop(1)
print ("The list is now : ", list1)

The output result of the above example is as follows:

列表现在为 :  ['Google', 'Example']
列表现在为 :  ['Google']

A queue is a first-in, first-out (FIFO) data structure. We can use lists to implement the basic functions of a queue.

  • append()The method adds an element to the end of the queue.
  • pop()The method removes an element from the beginning of the queue and returns it.

Example

queue = []

# Add elements to the end of the queue
queue.append('A')
queue.append('B')
queue.append('C')

# Remove elements from the beginning of the queue and return them
print(queue.pop(0))  # A
print(queue.pop(0))  # B
print(queue.pop(0))  # C

In the above example, we created an empty list as a queue, then used the append() method to add three elements to the end of the queue. Next, we used the pop() method to remove elements from the beginning of the queue and return them. Since a queue is a first-in, first-out data structure, the output we get is 'A', 'B', and 'C'.

Python3 列表Python3 Lists

Other Extensions