Containers
-
List Slicing
You can retrieve ranges of values (“slices”) from a list using a start:end syntax. All items will be included in the list that’s returned, from the start index up to (but not including) the end index. If a third argument is used, it specifies a step size. Default Slice Values All three of these slice…
-
Dictionary Comprehensions
You can create sets and dictionaries using comprehensions, just like lists. With dictionaries you need to use a key:value syntax to specify the keys and values. Here the keys are the numbers 0-4 and the values are the squares of those numbers.
-
List Comprehensions
List comprehensions are a convenient way to generate lists. Here’s a simple example. Note that the syntax used is like a for loop, except we have to also place the loop variable at the start to specify what should actually be added to the list. We can easily change what we add to the list.…
-
Python Dictionaries
Python dictionaries are basically lookup tables. They associate a set of keys with corresponding values. In many other programming languages they are known as ‘maps’. A dictionary is a bit like a set of key-value pairs. As with a set, very efficient to check whether a dictionary contains a particular key. However, unlike a set,…
-
Python Sets
Sets are unordered collections of unique objects. A set cannot store two equal objects. This makes them particularly useful for removing duplicates from collections of items. Since sets do not maintain any particular order, you cannot access items via an index (like with lists or tuples). However, you can iterate over them, and checking if…
-
Python Lists
Lists are mutable ordered containers. They’re similar to tuples, except they can be modified. They keep objects in the order you add them. Adding Items to Lists We can always add new items to a list. If you want to start with an empty list, you can simply use empty square brackets [] or you…
-
Python Tuples
A Python tuple can store an ordered collection of objects, which do not all have to have the same type. The objects remain in the order you put them in. You can access particular objects within the tuple using an index which starts at zero. Tuples are immutable; you can’t add, change or remove objects…
-
Python’s Four Main Containers
Python has four built-in classes that are used to create objects that store other objects. They are: tuple, list, set and dictionary. We’ll cover them all in detail in the following pages, but here’s a brief summary of what they’re used for and some example code.