📜  Python List.reverse()方法

📅  最后修改于: 2020-10-30 05:52:23             🧑  作者: Mango

Python列表reverse()方法

Python reverse()方法可反转列表中的元素。如果列表为空,则仅返回一个空列表。反转后,列表的最后一个索引值将出现在0索引处。下面给出了示例和方法签名。

签名

reverse()

参量

没有参数

返回

它返回None。

让我们看一些reverse()方法的例子来了解它的功能。

Python列表reverse()方法示例1

首先让我们看一个简单的示例来反转列表。它以相反的顺序打印所有元素。

# Python list reverse() Method
# Creating a list
apple = ['a','p','p','l','e']
# Method calling
apple.reverse() # Reverse elements of the list
# Displaying result
print(apple)

输出:

['e', 'l', 'p', 'p', 'a']

Python List reverse()方法示例2

如果列表为空,则返回空列表。请参见下面的示例。

# Python list reverse() Method
# Creating a list
apple = []
# Method calling
apple.reverse() # Reverse elements of the list
# Displaying result
print(apple)

输出:

[]

Python列表reverse()方法示例3

这个例子表明,反转后元素的顺序没有改变。

# Python list reverse() Method
# Creating a list
apple = ['e', 'l', 'p', 'p', 'a']
apple2 = ['a', 'p', 'p', 'l', 'e']
# Calling Method
apple.reverse()
# Comparing both lists
if apple == apple2:
    print("Both are equal")
else: print("Not equal")

输出:

Both are equal