Book Image

Modern Python Cookbook

Book Image

Modern Python Cookbook

Overview of this book

Python is the preferred choice of developers, engineers, data scientists, and hobbyists everywhere. It is a great scripting language that can power your applications and provide great speed, safety, and scalability. By exposing Python as a series of simple recipes, you can gain insight into specific language features in a particular context. Having a tangible context helps make the language or standard library feature easier to understand. This book comes with over 100 recipes on the latest version of Python. The recipes will benefit everyone ranging from beginner to an expert. The book is broken down into 13 chapters that build from simple language concepts to more complex applications of the language. The recipes will touch upon all the necessary Python concepts related to data structures, OOP, functional programming, as well as statistical programming. You will get acquainted with the nuances of Python syntax and how to effectively use the advantages that it offers. You will end the book equipped with the knowledge of testing, web services, and configuration and application integration tips and tricks. The recipes take a problem-solution approach to resolve issues commonly faced by Python programmers across the globe. You will be armed with the knowledge of creating applications with flexible logging, powerful configuration, and command-line options, automated unit tests, and good documentation.
Table of Contents (18 chapters)
Title Page
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Using tuples of items


What's the best way to represent simple (x,y) and (r,g,b) groups of values? How can we keep things which are pairs such as latitude and longitude together?

Getting ready

In the String parsing with regular expressions recipe, we skipped over an interesting data structure.

We had data that looked like this:

>>> ingredient = "Kumquat: 2 cups"

We parsed this into the meaningful data using a regular expression like this:

>>> import re>>> ingredient_pattern = re.compile(r'(?P<ingredient>\w+):\s+(?P<amount>\d+)\s+(?P<unit>\w+)')>>> match = ingredient_pattern.match( ingredient )>>> match.groups()('Kumquat', '2', 'cups')

The result is a tuple object with three pieces of data. There are lots of places where this kind of grouped data come in handy.

How to do it...

We'll look at two aspects to this: putting things into tuples and getting things out of tuples.

Creating tuples

There are lots of places where Python creates tuples of data for us. In the Getting ready section of the String Parsing with Regular Expressions recipe we showed how a regular expression match object will create a tuple of text that was parsed from a string.

We can create our own tuples, too. Here are the steps:

  1. Enclose the data in ().
  2. Separate the items with a ,.
>>> from fractions import Fraction>>> my_data = ('Rice', Fraction(1/4), 'cups')

There's an important special case for the one-tuple, or singleton. We have to include an extra , even when there's only one item in the tuple.

>>> one_tuple = ('item', )>>> len(one_tuple)1

Note

The () characters aren't always required. There are a few times where we can omit them. It's not a good idea to omit them, but we can see funny things when we have an extra comma: >>> 355,(355,)

The extra comma after 355 makes the value into a singleton tuple.

Extracting items from a tuple

The idea of a tuple is to be a container with a number of items that's fixed by the problem domain: for example, (red, green, blue) color numbers. The number of items is always three.

In our example, we've got an ingredient, and amount, and units. This must be a three-item collection. We can look at the individual items two ways:

  • By index position: Positions are numbered starting with zero from the left:
>>> my_data[1]Fraction(1, 4)
  • Using multiple assignment:
>>> ingredient, amount, unit = my_data>>> ingredient'Rice'>>> unit'cups'

Tuples—like strings—are immutable. We can't change the individual items inside a tuple. We use tuples when we want to keep the data together.

How it works...

Tuples are one example of the more general class of Sequence. We can do a few things with sequences.

Here's an example tuple that we can work with:

>>> t = ('Kumquat', '2', 'cups')

Here are some operations we can perform on this tuple:

  • How many items in t?
>>> len(t)3
  • How many times does a particular value appear in t?
>>> t.count('2')1
  • Which position has a particular value?
>>> t.index('cups')2>>> t[2]'cups'
  • When an item doesn't exist, we'll get an exception:
>>> t.index('Rice')Traceback (most recent call last):  File "<stdin>", line 1, in <module>ValueError: tuple.index(x): x not in tuple
  • Does a particular value exist?
>>> 'Rice' in tFalse

There's more

A tuple, like a string, is a sequence of items. In the case of a string, it's a sequence of characters. In the case of a tuple, it's a sequence of many things. Because they're both sequences, they have some common features. We've noted that we can pluck out individual items by their index position. We can use the index() method to locate the position of an item.

The similarities end there. A string has many methods to create a new string that's a transformation of a string, plus methods to parse strings, plus methods to determine the content of the strings. A tuple doesn't have any of these bonus features. It's—perhaps—the simplest possible data structure.

See also...

  • We've looked at one other sequence, the list, in the Building complex strings from lists of characters recipe
  • We'll also look at sequences in Chapter 4, Built-in Data Structures – list, tuple, set, dict