您已经了解了如何创建列表。在本课程中,您将了解到列表是有序的并且可以包含任意对象的集合。定义列表时使用的顺序在列表的生命周期内保持不变。包含相同元素但顺序不同的列表是不同的:
>>>>>> a = ['spam', 'egg', 'bacon', 'tomato']
>>> a
['spam', 'egg', 'bacon', 'tomato']
>>> b = ['egg', 'bacon', 'tomato', 'spam']
>>> b
['egg', 'bacon', 'tomato', 'spam']
>>> a == b
False
>>> a is b
False
>>> [1, 2, 3, 4] == [4, 1, 3, 2]
False
>>>>>> a = [2, 4, 6, 8]
>>> a
[2, 4, 6, 8]
>>> type(a)
<class 'list'>
>>> a = [21.42, 'spam', 3, 4, 'egg', False, 3.14159]
>>> a
[21.42, 'spam', 3, 4, 'egg', False, 3.14159]
>>> type(a)
<class 'list'>
>>> int
<class 'int'>
>>> len
<built-in function len>
>>> def foo():
... pass
...
>>> foo
<function foo at 0x108aacd90>
>>> import math
>>> math
<module 'math' from '/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/lib-dynload/math.cpython-37m-darwin.so'>
>>> a = [int, len, foo, math]
>>> a
[<class 'int'>, <built-in function len>, <function foo at 0x108aacd90>, <module 'math' from '/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/lib-dynload/math.cpython-37m-darwin.so'>]
>>>>>> a = []
>>> a
[]
>>> type(a)
<class 'list'>
>>> a = ['spam']
>>> a
['spam']
>>> type(a)
<class 'list'>
>>> a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, ... 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, ... 41, 42, 43, 44, 45, 46, 47, 48, 49, 50]
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50]
>>> type(a)
<class 'list'>