Collections

Lists, Tuples, Dictionaries

Lists, Tuples, Dictionaries are all collection data types, meaning that they can store multiple different items within one entry

Here are some formal definitions of these data types and some examples:

  • Lists are collections that are ordered, changeable, and allow duplicates.
  • Tuples are collections that are ordered, unchangeable, and allow duplicates.
  • Dictionaries are collections that are unordered, changeable, indexed, and do not allow duplicates.
[1, 2, 2, 3, 4, 5, 6, 23, 100, "John"] # This is a list

(1, 2, 3, 4, 4, 5, 5, 5, 6, "Hello") # This is a Tuple

{1:"hello", 2:"goodbye", "name":"John Doe"} # This is a dictionary

With that out of the way, let’s delve deeper into what those terms actually mean.

Ordered and Indexed

Ordered

In Python, both Lists and Tuples are ordered, meaning that each item within the collection has a specific number attached to them. We call this number the index of the element.

Heres a list and a tuple with the same elements

['a', 'b', 'c', 1, 2, 3]

('a', 'b', 'c', 1 , 2, 3)

In this example, the first element of both the list and tuple is the string ‘a’, and they share the same index, namely index 0.

All lists and tuples start at index 0 and then increment by 1 for each next element

Thus the letter ‘b’ has index 1, ‘c’ index 2, and so on.

Indexed

When we say Dictionary is unordered, it means that the elements inside the collection do not have an index associated with them.

However, Dictionaries do have a way of relating elements.

Dictionaries have two different attributes: Keys and Definitions

Lets breakdown the structure of a dictionary

{
    key1 : definition1,
    key2 : definition2
}

# This is equivalent to {key1 : definition1, key2 : definition2} but is easier to read

A good way of thinking about dictionaries in Python is to think of dictionaries in language!

Keys are like words in a standard dictionary and each word will have a definition. In Python, both the keys and definitions can be of any data type.

They way we access elements within a dictionary is to use the key as an index, similar to how we would look up a word in a real dictionary.

For example:

{
    'name' : "John",
    'age' : 26
}

If I wanted to see to access the String “John”, I would use the name index.

Changeable vs Unchangeable

The ability to change, often known as mutability, refers to the ability to alter the data within a collection.

Both lists and dictionaries are mutable data types, whereas tuples are not.

Duplicates

Duplicate entries, meaning the same element, can appear multiple times within lists and tuples.

Dictionaries cannot have duplicate keys, however, they can have duplicate definitions.