Thanks to visit codestin.com
Credit goes to www.oreilly.com

Skip to Content
Python Cookbook, 3rd Edition
book

Python Cookbook, 3rd Edition

by David Beazley, Brian K. Jones
May 2013
Codestin Search AppIntermediate to advanced
706 pages
14h 42m
English
O'Reilly Media, Inc.
Content preview from Python Cookbook, 3rd Edition

Chapter 1. Data Structures and Algorithms

Python provides a variety of useful built-in data structures, such as lists, sets, and dictionaries. For the most part, the use of these structures is straightforward. However, common questions concerning searching, sorting, ordering, and filtering often arise. Thus, the goal of this chapter is to discuss common data structures and algorithms involving data. In addition, treatment is given to the various data structures contained in the collections module.

1.1. Unpacking a Sequence into Separate Variables

Problem

You have an N-element tuple or sequence that you would like to unpack into a collection of N variables.

Solution

Any sequence (or iterable) can be unpacked into variables using a simple assignment operation. The only requirement is that the number of variables and structure match the sequence. For example:

>>> p = (4, 5)
>>> x, y = p
>>> x
4
>>> y
5
>>>

>>> data = [ 'ACME', 50, 91.1, (2012, 12, 21) ]
>>> name, shares, price, date = data
>>> name
'ACME'
>>> date
(2012, 12, 21)

>>> name, shares, price, (year, mon, day) = data
>>> name
'ACME'
>>> year
2012
>>> mon
12
>>> day
21
>>>

If there is a mismatch in the number of elements, you’ll get an error. For example:

>>> p = (4, 5)
>>> x, y, z = p
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: need more than 2 values to unpack
>>>

Discussion

Unpacking actually works with any object that happens to be iterable, not just tuples or lists. This includes strings, ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Effective Python: 125 Specific Ways to Write Better Python, 3rd Edition

Effective Python: 125 Specific Ways to Write Better Python, 3rd Edition

Brett Slatkin

Publisher Resources

ISBN: 9781449357337Errata PageSupplemental Content