L = [42, 43, "hello", 44]
print("L[0] ==", L[0], "and L[2] ==", L[2])
L[0] == 42 and L[2] == hello
Here is a more interesting example -- let's define a function
def f(n):
return n + 42
If we go simply f, rather than f(5) for example, Python will just tell us that f is a function:
f
<function __main__.f>
We can have f be an element of the list L:
L = [2, 4, 7, f, 6]
L[3]
<function __main__.f>
L[3] evaluates to f in the same way that L[0] would evaluate to 2. We can, of course, call f by referring to it as L[3]:
L[3](8)
50
Of course, we didn't have to do anything as complicated as that in order to refer to f by another name:
g = f
g(10)
52
Here's another example of complex objects' being elements of lists:
L = [42, 43, [45, 46], 47]
print(L[2])
[45, 46]
L[2] is the list [45, 46]. We can access 46 using:
L[2][1]
46
L[2] evaluates to the list [45, 46], and then L[2][1] is the second element of L[2]. Note that the following works similarly:
[45, 46][1]
46
Here is a usual situation: we want to define a table. We can do this by creating a list of lists (i.e., a list whose elements are lists). We can think of it as a list of rows.
L = [[1, 2, 3, 4],
[1, 0, 1, 0],
[2, 2, 3, 5]]
We typeset things so that it's apparent that L represents a table. However, as far as Python is concerned, L is just an orindary list of lists.
L
[[1, 2, 3, 4], [1, 0, 1, 0], [2, 2, 3, 5]]
Now, how do we access the 5 in the third row? To get the third row, we go
L[2]
[2, 2, 3, 5]
To get the entry 5 at the end of the row, we need the element at index 3:
L[2][3]
5
Here is an easy (if not ideal) way to display L as a table:
for row in L:
print(row)
[1, 2, 3, 4] [1, 0, 1, 0] [2, 2, 3, 5]
row is first the first list, then the second list, and so on. Notw that we had to do this because Python by default doesn't print L is if it were a table:
print(L)
[[1, 2, 3, 4], [1, 0, 1, 0], [2, 2, 3, 5]]
Consider the following:
L = [[[[[]]]]]
L is a list of length 1, with just one element:
L[0]
[[[[]]]]
We can go further:
L[0][0]
[[[]]]
L[0][0][0]
[[]]
L[0][0][0][0]
[]
That's as far as we can go:
L[0][0][0][0][0]
--------------------------------------------------------------------------- IndexError Traceback (most recent call last) <ipython-input-21-fa867e755bc3> in <module>() ----> 1 L[0][0][0][0][0] IndexError: list index out of range
You cannot access the first element of [], since [] contains no elements at all.