Containers#
In the previous section, we have introduced numerics of type int
and float
, as well as text variable. Often we would like to group many of numerics or strings together to perform larger operations. This section introduces classes of containers to group values together.
List#
Lists are generic containers for other objects, which can be of any type. They are created with square brackets []
.
a_list = [1.0, 2, "abc"]
Here are a few important methods that can used on a list
.
Indexing (accessing) elements of the list (count starts at 0)
a_list[0]
1.0
Adding (appending) to the list.
a_list += ["new"]
a_list
[1.0, 2, 'abc', 'new']
Removing an element from the list using the
pop
method with index
a_list.pop(0)
a_list
[2, 'abc', 'new']
Finding the
index
of an element within the list. The same method applies to string objects.
a_list.index("abc")
1
Dictionary#
Dictionaries (dict
) are also containers for objects but give an additional level of structure over lists as every
value of the dictionary is indexed by a key
. A dictionary is created with a list of key: value
pairs within
braces {}
.
my_dict = {"integer": 2}
Here are a few important methods that can used on a dict
.
Accessing values using the key
my_dict["integer"]
2
Adding entries
my_dict["new"] = 123
my_dict
{'integer': 2, 'new': 123}
Removing entries
del my_dict["new"]
my_dict
{'integer': 2}
Looping over keys
list(my_dict)
['integer']
Looping over values
list(my_dict.values())
[2]
Looping over both keys and values
list(my_dict.items())
[('integer', 2)]
Copyright (c) 2022 Mira Geoscience Ltd.