You’ve already seen how to create a list. In this lesson, you’ll learn that lists are ordered and can contain a collection of arbitrary objects. The order used when defining a list is maintained for the lifetime of the list. Lists that contain the same elements, but in a different order, are not the same:
>>> 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 list can contain arbitrary objects. The elements of a list can all be the same type or can contain any assortment of varying types. Lists can contain complex objects such as functions, classes, or modules:
>>> 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 list can contain any number of objects, from zero, to as many as your computer’s memory will allow. A list with a single object is sometimes referred to as a singleton list:
>>> 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'>
The objects in a list don’t need to be unique. An object can appear multiple times within a list:
>>> a = ['bark', 'meow', 'woof', 'bark', 'cheep', 'bark']
>>> a
['bark', 'meow', 'woof', 'bark', 'cheep', 'bark']
>>> type(a)
<class 'list'>
If you want to learn more about bpython
, the REPL(Read–Eval–Print Loop) tool used in these videos, then you can check out these links:
JVargas on Dec. 15, 2019
Thanks to let us know about bpython.