Lists & Dictionaries

This is part of “An intro to Python” series of posts, with content from the Enki app. If you stumbled upon this, you can start from the beginning.

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.

Learn More

Andrei Calabangiu

Content Manager

About Enki

  • AI-powered, customized 1:1 coaching
  • Fully customized to team needs
  • Pay only for active learners and results

More articles