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?

Self-Massage Tool

Aching back from coding all day? Try Back Problems

Relieve spasms, tight muscles, trigger points and pressure points with the Body Back Buddy! This trigger point massage is designed to help you self-message any area of your body - especially those that are hard to reach. Keeping your muscles relaxes and out of contraction is importan in helping to reduce pain and prevent muscle injury.

$ Check price
29.9529.95Amazon 4.5 logo(3,443+ reviews)

More Back Problems resources

Learn to be a Pythonista!

Programming Python

Learn to be a Pythonista! Try Python

Programming Python shows in-depth tutorials on the language's number of application domains including: system administration, GUIs, the Web, networking, front-end scripting layers, and more. This book focuses on commonly used tools and libraries to give you a comprehensive understanding of Python’s many roles in practical, real-world programming.

$ Check price
64.9964.99Amazon 4 logo(56+ reviews)

More Python resources