01. Introduction to Collections

We have previously seen the Python primitive data types - booleans, numbers and strings. Let's now look at a little more advanced data types that are able to group multiple items or elements together. These are known as collections or compound data types.

Three categories of collections

Python collections may be categorized into sets, sequences and mappings.

1) Sets

A set is an ordered collection containing no duplicates. For example, a collection of all possible letter grades that one may receive can be part of the set grades = {A, B, C, D, F}.

2) Sequences

A sequence is an ordered collection of data types. Since they are ordered, we may use numerical indices to access them. One example of a sequence that we have already seen is the string. Other examples include bytes, byte arrays, lists and tuples. An example of a sequence is a list, such as fib = [1, 1, 2, 3, 5, 8].

3) Mappings

Mappings map a key to some value. Each entry exists as a key-value pair. You may have already heard of Python's dictionary data type. Here, we can use a key to look up a resulting value, much like an associative array.

An example of a mapping can be a DNA letter code to its name. dna = { 'A': 'Adenine', 'C': 'Cytosine', 'G': 'Guanine', 'T': 'Thymine'}.

Common Functions for Collections

Here is a list of common functions used with collections. Some of these may look familiar, as we have seen them when covering strings. We'll assume that the variable c contains a collection.

Check if an element exists in a collection.
not in
Check if element does not exist in collection.
Checks if any values in the collection is true.
Check if all values in the collection are true.
Check number of items in the collection.
Takes the max value within collection.
Takes the min value within collection.
Checks if collection is sorted.

Learn to be a Pythonista!

Learn Python in One Day

Learn to be a Pythonista! Try Python

Have you always wanted to learn computer programming but are afraid it'll be too difficult for you? Or you're familiar with some programming but are interested in learning Python fast? Then this book is for you. You no longer have to waste your time and money learning Python from lengthy books, expensive online courses or complicated Python tutorials.

$ Check price
11.9711.97Amazon 4 logo(185+ reviews)

More Python resources

Aching back from coding all day?

Acupressure Mat & Pillow

Aching back from coding all day? Try Back Problems

Relieve your stress, back, neck and sciatic pain through 1,782 acupuncture points for immediate neck pain relief. Made for lower, upper and mid chronic back pain treatment, and improves circulation, sleep, digestion and quality of life.

$$ Check price
144.87144.87Amazon 4.5 logo(1,890+ reviews)

More Back Problems resources