Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Modern Python Cookbook

You're reading from   Modern Python Cookbook 130+ updated recipes for modern Python 3.12 with new techniques and tools

Arrow left icon
Product type Paperback
Published in Jul 2024
Publisher Packt
ISBN-13 9781835466384
Length 818 pages
Edition 3rd Edition
Languages
Arrow right icon
Author (1):
Arrow left icon
Steven F. Lott Steven F. Lott
Author Profile Icon Steven F. Lott
Steven F. Lott
Arrow right icon
View More author details
Toc

Table of Contents (20) Chapters Close

Preface 1. Chapter 1 Numbers, Strings, and Tuples FREE CHAPTER 2. Chapter 2 Statements and Syntax 3. Chapter 3 Function Definitions 4. Chapter 4 Built-In Data Structures Part 1: Lists and Sets 5. Chapter 5 Built-In Data Structures Part 2: Dictionaries 6. Chapter 6 User Inputs and Outputs 7. Chapter 7 Basics of Classes and Objects 8. Chapter 8 More Advanced Class Design 9. Chapter 9 Functional Programming Features 10. Chapter 10 Working with Type Matching and Annotations 11. Chapter 11 Input/Output, Physical Format, and Logical Layout 12. Chapter 12 Graphics and Visualization with Jupyter Lab 13. Chapter 13 Application Integration: Configuration 14. Chapter 14 Application Integration: Combination 15. Chapter 15 Testing 16. Chapter 16 Dependencies and Virtual Environments 17. Chapter 17 Documentation and Style 18. Other Books You May Enjoy
19. Index

1.9 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 that are pairs, such as latitude and longitude, together?

1.9.1 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 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 can come in handy.

1.9.2 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 you 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 ,.

    >>> 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 the , even when there’s only one item in the tuple:

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

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.

It’s the comma that creates a tuple of values. This means we can see funny things when we have an extra comma:

>>> 355, 
 
(355,)

The comma after 355 turns the value into a singleton tuple.

We can also create a tuple by conversion from another sequence. For example, tuple([355]) creates a singleton tuple from a singleton list.

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, for (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 in two ways:

  • By index position; that is, 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.

1.9.3 How it works...

Tuples are one example of the more general Sequence class. 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): 
     
    ... 
     
    ValueError: tuple.index(x): x not in tuple
  • Does a particular value exist?

    >>> ’Rice’ in t 
     
    False

1.9.4 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 it can use 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.

1.9.5 See also

  • We looked at one other sequence, the list, in the Building complicated strings from lists of strings recipe.

  • We’ll also look at sequences in Chapter 4.

You have been reading a chapter from
Modern Python Cookbook - Third Edition
Published in: Jul 2024
Publisher: Packt
ISBN-13: 9781835466384
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 €18.99/month. Cancel anytime