Lists
Lists are sequences of elements. A list can contain any number of elements, and the elements of the list can be any type of object. Lists can also be thought of as arrays. The number of elements in a list can increase or decrease as elements are added, removed, or replaced.
Examples
[] |
Any empty list. |
[1] |
A list with a single element, an integer. |
["Mike", 10, "Don", 20] |
A list with four elements, two string elements and two integer elements. |
[[],[7],[8,9]] |
A list of lists. Each sub-list is either an empty list or a list of integer elements. |
|
A list of integers. This example demonstrates the use of variables and expressions. |
You can assign a list to a variable. For example:
mylist1 = ["one", "two", "three"]
You can then access specific elements of the list. For example:
mylist[0]
This will result in the following output:
one
The number in the brackets ([]
) is known as an index and refers to
a particular element of the list. The elements of a list are indexed starting from 0.
You can also select a range of elements of a list; this is called slicing. For
example, x[1:3]
selects the second and third elements of x
. The
end index is one past the selection.