Modern Python Cookbook
eBook - ePub

Modern Python Cookbook

133 recipes to develop flawless and expressive programs in Python 3.8, 2nd Edition

  1. 822 pages
  2. English
  3. ePUB (mobile friendly)
  4. Available on iOS & Android
eBook - ePub

Modern Python Cookbook

133 recipes to develop flawless and expressive programs in Python 3.8, 2nd Edition

About this book

Complete recipes spread across 15 chapters to help you overcome commonly faced issues by Python for everybody across the globe. Each recipe takes a problem-solution approach to resolve for effective Python.

Key Features

  • Develop expressive and effective Python programs
  • Best practices and common idioms through carefully explained recipes
  • Discover new ways to apply Python for data-focused development
  • Make use of Python's optional type annotations

Book Description

Python is the preferred choice of developers, engineers, data scientists, and hobbyists everywhere. It is a great language that can power your applications and provide great speed, safety, and scalability. It can be used for simple scripting or sophisticated web applications. By exposing Python as a series of simple recipes, this book gives you insight into specific language features in a particular context. Having a tangible context helps make the language or a given standard library feature easier to understand.

This book comes with 133 recipes on the latest version of Python 3.8. The recipes will benefit everyone, from beginners just starting out with Python to experts. You'll not only learn Python programming concepts but also how to build complex applications.

The recipes will touch upon all necessary Python concepts related to data structures, object oriented programming, functional programming, and statistical programming. You will get acquainted with the nuances of Python syntax and how to effectively take advantage of it.

By the end of this Python book, you will be equipped with knowledge of testing, web services, configuration, and application integration tips and tricks. You will be armed with the knowledge of how to create applications with flexible logging, powerful configuration, command-line options, automated unit tests, and good documentation.

What you will learn

  • See the intricate details of the Python syntax and how to use it to your advantage
  • Improve your coding with Python readability through functions
  • Manipulate data effectively using built-in data structures
  • Get acquainted with advanced programming techniques in Python
  • Equip yourself with functional and statistical programming features
  • Write proper tests to be sure a program works as advertised
  • Integrate application software using Python

Who this book is for

The Python book is for web developers, programmers, enterprise programmers, engineers, and big data scientists. If you are a beginner, this book will get you started. If you are experienced, it will expand your knowledge base. A basic knowledge of programming would help.

Frequently asked questions

Yes, you can cancel anytime from the Subscription tab in your account settings on the Perlego website. Your subscription will stay active until the end of your current billing period. Learn how to cancel your subscription.
At the moment all of our mobile-responsive ePub books are available to download via the app. Most of our PDFs are also available to download and we're working on making the final remaining ones downloadable now. Learn more here.
Perlego offers two plans: Essential and Complete
  • Essential is ideal for learners and professionals who enjoy exploring a wide range of subjects. Access the Essential Library with 800,000+ trusted titles and best-sellers across business, personal growth, and the humanities. Includes unlimited reading time and Standard Read Aloud voice.
  • Complete: Perfect for advanced learners and researchers needing full, unrestricted access. Unlock 1.4M+ books across hundreds of subjects, including academic and specialized titles. The Complete Plan also includes advanced features like Premium Read Aloud and Research Assistant.
Both plans are available with monthly, semester, or annual billing cycles.
We are an online textbook subscription service, where you can get access to an entire online library for less than the price of a single book per month. With over 1 million books across 1000+ topics, we’ve got you covered! Learn more here.
Look out for the read-aloud symbol on your next book to see if you can listen to it. The read-aloud tool reads text aloud for you, highlighting the text as it is being read. You can pause it, speed it up and slow it down. Learn more here.
Yes! You can use the Perlego app on both iOS or Android devices to read anytime, anywhere — even offline. Perfect for commutes or when you’re on the go.
Please note we cannot support devices running on iOS 13 and Android 7 or earlier. Learn more about using the app.
Yes, you can access Modern Python Cookbook by Steven F. Lott in PDF and/or ePUB format, as well as other popular books in Computer Science & Programming. We have over one million books available in our catalogue for you to explore.

Information

4

Built-In Data Structures Part 1: Lists and Sets

Python has a rich collection of built-in data structures. These data structures are sometimes called "containers" or "collections" because they contain a collection of individual items. These structures cover a wide variety of common programming situations.
We'll look at an overview of the various collections that are built-in and what problems they solve. After the overview, we will look at the list and set collections in detail in this chapter, and then dictionaries in Chapter 5, Built-In Data Structures Part 2: Dictionaries.
The built-in tuple and string types have been treated separately. These are sequences, making them similar in many ways to the list collection. In Chapter 1, Numbers, Strings, and Tuples, we emphasized the way strings and tuples behave more like immutable numbers than like the mutable list collection.
The next chapter will look at dictionaries, as well as some more advanced topics also related to lists and sets. In particular, it will look at how Python handles references to mutable collection objects. This has consequences in the way functions need to be defined that accept lists or sets as parameters.
In this chapter, we'll look at the following recipes, all related to Python's built-in data structures:
  • Choosing a data structure
  • Building lists – literals, appending, and comprehensions
  • Slicing and dicing a list
  • Deleting from a list – deleting, removing, popping, and filtering
  • Writing list-related type hints
  • Reversing a copy of a list
  • Building sets – literals, adding, comprehensions, and operators
  • Removing items from a set – remove(), pop(), and difference
  • Writing set-related type hints

Choosing a data structure

Python offers a number of built-in data structures to help us work with collections of data. It can be confusing to match the data structure features with the problem we're trying to solve.
How do we choose which structure to use? What are the features of lists, sets, and dictionaries? Why do we have tuples and frozen sets?

Getting ready

Before we put data into a collection, we'll need to consider how we'll gather the data, and what we'll do with the collection once we have it. The big question is always how we'll identify a particular item within the collection.
We'll look at a few key questions that we need to answer to decide which of the built-in structures is appropriate.

How to do it...

  1. Is the programming focused on simple existence? Are items present or absent from a collection? An example of this is validating input values. When the user enters something that's in the collection, their input is valid; otherwise, their input is invalid. Simple membership tests suggest using a set:
    def confirm() -> bool: yes = {"yes", "y"} no = {"no", "n"} while (answer := input("Confirm: ")).lower() not in (yes|no): print("Please respond with yes or no") return answer in yes 
    A set holds items in no particular order. Once an item is a member, we can't add it again:
    >>> yes = {"yes", "y"} >>> no = {"no", "n"} >>> valid_inputs = yes | no >>> valid_inputs.add("y") >>> valid_inputs {'yes', 'no', 'n', 'y'} 
    We have created a set, valid_inputs, by performing a set union using the | operator among sets. We can't add another y to a set that already contains y. There is no exception raised if we try such an addition, but the contents of the set don't change.
    Also, note that the order of the items in the set isn't exactly the order in which we initially provided them. A set can't maintain any particular order to the items; it can only determine if an item exists in the set. If order matters, then a list is more appropriate.
  2. Are we going to identify items by their position in the collection? An example includes the lines in an input file—the line number is its position in the collection. When we must identify an item using an index or position, we must use a list:
    >>> month_name_list = ["Jan", "Feb", "Mar", "Apr", ... "May", "Jun", "Jul", "Aug", ... "Sep", "Oct", "Nov", "Dec"] >>> month_name_list[8] 'Sep' >>> month_name_list.index("Feb") 
    We have created a list, month_name_list, with 12 string items in a specific order. We can pick an item by providing its position. We can also use the index() method to locate the index of an item in the list. List index values in Python always start with a position of zero. While a list has a simple membership test, the test can be slow for a very large list, and a set might be a better idea if many such tests will be needed.
    If the number of items in the collection is fixed—for example, RGB colors have three values—this suggests a tuple instead of a list. If the number of items will grow and change, then the list collection is a better choice than the tuple collection.
  3. Are we going to identify the items in a collection by a key value that's distinct from the item's position? An example might include a mapping between strings of characters—words...

Table of contents

  1. Preface
  2. Numbers, Strings, and Tuples
  3. Statements and Syntax
  4. Function Definitions
  5. Built-In Data Structures Part 1: Lists and Sets
  6. Built-In Data Structures Part 2: Dictionaries
  7. User Inputs and Outputs
  8. Basics of Classes and Objects
  9. More Advanced Class Design
  10. Functional Programming Features
  11. Input/Output, Physical Format, and Logical Layout
  12. Testing
  13. Web Services
  14. Application Integration: Configuration
  15. Application Integration: Combination
  16. Statistical Programming and Linear Regression
  17. Index
  18. Other Books You May Enjoy
  19. Index