Book Image

Daniel Arbuckle's Mastering Python

By : Daniel Arbuckle
Book Image

Daniel Arbuckle's Mastering Python

By: Daniel Arbuckle

Overview of this book

Daniel Arbuckle's Mastering Python covers the basics of operating in a Python development environment, before moving on to more advanced topics. Daniel presents you with real-world solutions to Python 3.6 and advanced-level concepts, such as reactive programming, microservices, ctypes, and Cython tools. You don't need to be familiar with the Python language to use this book, as Daniel starts with a Python primer. Throughout, Daniel highlights the major aspects of managing your Python development environment, shows you how to handle parallel computation, and helps you to master asynchronous I/O with Python 3.6 to improve performance. Finally, Daniel will teach you the secrets of metaprogramming and unit testing in Python, helping you acquire the perfect skillset to be a Python expert. Daniel will get you up to speed on everything from basic programming practices to high-end tools and techniques, things that will help set you apart as a successful Python programmer.
Table of Contents (13 chapters)

Python's built-in data structures and comprehensions

Now, let's take a look at the core data structure types of Python. These aren't the only data structures available, of course, because it's fairly easy to create data structures using classes. However, these data structures are built right into the heart of Python and they're highly efficient, so it's a good idea to be very familiar with them.

The first thing to understand is that data structures are themselves data values similar to a filing cabinet-they're one thing that contains many things. Like any other data value, they can be stored in a variable or used as part of an expression.

Dictionaries

The first data structure we're going to look at is Python's dictionary. A dictionary consists of any number of key-value pairs. The key can be used to get or set the value or remove the pair from the dictionary entirely.

Similar data structures in other languages are sometimes called maps or hash tables.

There are several ways to create a dictionary in Python. The simplest is to use a dictionary expression, which is just a pair of curly brackets surrounding the key-value pairs we want in the dictionary. Each key-value pair is marked with a colon between the key and value, and each pair is separated by a comma, as shown in the following code example:

example_dict = {'a' :1, 'b' :2, 'c' :3} 

When this expression runs, the result is a dictionary object containing the keys and their values. We can also use the dict class to create dictionary objects:

another_dict = dict() 

If we don't want to use the special syntax to access one of the stored values in a dictionary, we use a lookup expression. This means that we place square brackets containing the key we want to look up after an expression that gives us the dictionary. Usually, this means, the name of the variable containing the dictionary, an open square bracket, a sub-expression that gives us the key, and then a closing square bracket:

example_dict['b'] 
2 

We can also use the dict.get function if we prefer not to use the special syntax:

example_dict.get('c') 
3 

List

The next data type we're going to look at is a list, which can be created with the list expression. A list expression is just a pair of square brackets surrounding the data values we want to store in the list, with each value separated by a comma. It is not necessary that each of the values be of the same type. The code example for a list is as follows:

In the preceding example, they're strings, but they could be numbers, or a list, or any other kind of data mixed together. We can use a lookup expression to retrieve data values.

Unlike with a dictionary though, the keys for a list are integers. That's because instead of associating key values with data values, a list just stores its data values in order. The key for the very first item in the list is 0. The key for the next item is 1, and so on. We can also use negative integers for the key. We still get a data value out, but it's counted from the end of the list instead of the beginning, with the item at -1 being the last item in the list.

We can use the list.append function to add a new item at the end of the list or its insert function to add a new item anywhere as shown in the following code:

The list will automatically grow to be large enough to hold all of the data we put into it.

Tuple

The next data structure we'll look at is the tuple. A tuple expression is any sequence of value expressions separated by commas if it happens in the place where the language wasn't already expecting to see a comma.

However, it's common and smart to put parentheses around most tuple expressions because it avoids ambiguity. The code example for tuple is as follows:

Like a list, data values can be retrieved from a tuple using numbers. However, we can't add more data to a tuple, and we cannot replace one data value with another.

Why would we want a data structure like that?

Well, there are several reasons. We can list them as follows:

  • First, because they are constant, tuples make good dictionary keys or set members, but we'll get to that in a while.
  • Second, they fill a different conceptual role than lists. We tend to expect every member of a list to be the same type, such as a list of names or a list of ages. Lists are sort of like columns of a database in that way. We tend to expect tuples to contain different types of data in each element, but we expect them to be related to each other, such as a name in the first element and an age in the second. To continue our analogy, tuples are something like rows in a database.
  • Third, tuples tend to be slightly more efficient for the computer to work with, both in terms of time and memory usage. So, in optimization situations, they are preferable to lists when they are sufficient for the task.

Set

The final data structure we'll look at is the set. A set is a collection of data values without keys; like a list, but in no particular order, like a dictionary. We can create a set using a set expression, which is a pair of curly brackets around comma-separated values, as shown in the following code example:

Locating a specific value in a set is fast, as is adding or removing a value, as shown in the following example:

Each value can only be in the set once. Sets support a bunch of mathematical operations, such as union and intersection, and are generally more useful than might be obvious at first, though we can't really prove that here in this section.

Comprehension

Python has a special kind of expression called a comprehension. Comprehensions are variations of the special syntax for creating dictionaries, lists, and sets.

Let's look at some examples. Here we see a list comprehension:

capitals = [x.upper() for x in example_list] 

What this expression does is that it creates a new list containing the uppercase versions of the words in the old list.

The first part after the opening square bracket is an x.upper() expression. This expression describes how to derive a member of the new list from a member of the old list. After that is the for keyword, then the name of the x variable we used in the first expression to represent the values from the old list. Then, the keyword is followed by the example_list expression that gives us the old list and the closing square bracket. The code output is as follows:

The dictionary and set comprehensions are very similar. If we want to use both the key and the value of an existing dictionary in a comprehension, we need to use the dict.items function, and dictionary comprehensions need to specify both the key and value separated by a colon, as shown in this example:

squares = {k: v ** 2 for k, v in example_dict.items()} 

As shown in the following screenshot, notice that the resulting data type depends on what sort of comprehension we used, not on what sort of data structure we used as the source of data:

We can use a list comprehension to create a list of data pulled from the values of a dictionary, for example, or, as we did here, we can use the set comprehension to create a set.

Tuples are slightly different, but only slightly. A tuple comprehension would look exactly like a different syntactic element called a generator expression. The code example for tuple comprehension is as follows:

Python's designers hate ambiguity; so instead, if we want the equivalent of a tuple comprehension, we pass a generator expression to a tuple constructor.

That's it for this quick introduction to Python's built-in data structures. In the next section, we're going to look at some useful, but possibly surprising, traits of functions and classes that are significantly different from C, C++, or Java.