Lists
The most common container data type is the list. Here, several entries are summarised in a fixed order:
coordinate = [1, 2, 3]
The entries can be of any data type:
mixed = [1, "two", 3.0]
Of course, this is not very advisable, but it shows the flexibility of a list. Mathematically, the list acts like a vector and can be generalised to a tensor, as a list can in turn contain a list:
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
elements = ["H", "He", "Li"]
elements[0] # Results in "H"
It should be noted here that indexing in Python always counts from 0. The last element can also be addressed with a negative index:
elements = ["H", "He", "Li"]
elements[-1] # Results in "Li"
Parts of a list can be addressed with a slice:
elements = ["H", "He", "Li", "Be", "B", "C"]
elements[1:4] # Results in ["He", "Li", "Be"]
Lists can be modified, e.g. by first creating an empty list with []
or list()
and then adding entries using .append()
:
elements = []
elements.append("H") # elements is now ["H"]
elements.append("He") # elements is now ["H", "He"]
Individual entries can be overwritten or removed:
elements = ["H", "He", "Li"]
elements[1] = "Helium" # elements is now ["H", "Helium", "Li"]
del elements[0] # elemente is now ["Helium", "Li"]
If you want to know the position of an entry, you can use .index()
:
elements = ["H", "He", "Li"]
elements.index("He") # Results in 1
The length of a list can be determined with len()
:
elements = ["H", "He", "Li"]
len(elements) # Results in 3
The list can also be sorted, but only if the comparison between the data types is permitted:
elements = ["one", "two", "three"]
elements.sort() # elements is now ["three", "one", "two"]
elements = ["one", 2, 3]
elements.sort() # TypeError: '<' not supported between instances of 'int' and 'str'
Whether a value is included can be checked with in
:
elements = ["H", "He", "Li"]
"He" in elements # Results in True
Mathematical operations such as +
and *
can also be applied to lists:
five_carbons = ["C"] * 5 # Results in ["C", "C", "C", "C", "C"]
both_lists = [1, 2, 3] + [4, 5, 6] # Results in [1, 2, 3, 4, 5, 6]