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.

Aching back from coding all day?

Foam Seat Cushion

Aching back from coding all day? Try Back Problems

This foam seat cushion relieves lowerback pain, numbness and pressure sores by promoting healthy weight distribution, posture and spine alignment. Furthermore, it reduces pressure on the tailbone and hip bones while sitting. Perfect for sitting on the computer desk for long periods of time.

$ Check price
99.9599.95Amazon 4.5 logo(9,445+ reviews)

More Back Problems resources

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