Lists are another sequential data type that act as containers for objects.
Lists are also separated by commas, but they must be wrapped in square brackets, [ ].
Lists are mutable, so items can be modified.
To add to a list you can use the append() method, passing whatever you want added as an argument in parentheses:
We can also use our index and count methods that we learnt about back in the tuple days on lists.
Dictionaries
The dictionary, dict, is Python’s main mapping type. Mapping objects are ones that contain key-value pairs.
In the example above, ’name’ and ’Jack’ are a key-value pair. ’name’ acts as the key, and ’Jack’ as the value.
Dictionaries are similar to lists because they are easily mutable — we can add and remove items.
Two important differences are:
- items can only be accessed using their key rather than their index.
- each key can only point to a single value. Keys must be unique.
To access items from a dict using keys:
The update() method merges the keys and values from one dictionary into another and overwrites values if the same key exists:
Remember — be careful when using update(), as a dictionary can’t have multiple entries with the same key.