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!

Introducing Python

Learn to be a Pythonista! Try Python

Easy to understand and fun to read, Introducing Python is ideal for beginning programmers as well as those new to the language. Author Bill Lubanovic takes you from the basics to more involved and varied topics, mixing tutorials with cookbook-style code recipes to explain concepts in Python 3. End-of-chapter exercises help you practice what you learned.

$ Check price
39.9939.99Amazon 4.5 logo(37+ reviews)

More Python resources

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