Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Daniel Arbuckle???s Mastering Python

You're reading from   Daniel Arbuckle???s Mastering Python Build powerful Python applications

Arrow left icon
Product type Paperback
Published in Jun 2017
Publisher Packt
ISBN-13 9781787283695
Length 274 pages
Edition 1st Edition
Languages
Tools
Arrow right icon
Author (1):
Arrow left icon
Daniel Arbuckle Daniel Arbuckle
Author Profile Icon Daniel Arbuckle
Daniel Arbuckle
Arrow right icon
View More author details
Toc

Table of Contents (13) Chapters Close

Preface 1. Python Primer 2. Setting Up FREE CHAPTER 3. Making a Package 4. Basic Best Practices 5. Making a Command-Line Utility 6. Parallel Processing 7. Coroutines and Asynchronous I/O 8. Metaprogramming 9. Unit Testing 10. Reactive Programming 11. Microservices 12. Extension Modules and Compiled Code

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.

lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image