Modern Python Cookbook
eBook - ePub

Modern Python Cookbook

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

Steven F. Lott

Compartir libro
  1. 822 páginas
  2. English
  3. ePUB (apto para móviles)
  4. Disponible en iOS y Android
eBook - ePub

Modern Python Cookbook

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

Steven F. Lott

Detalles del libro
Vista previa del libro
Índice
Citas

Información del libro

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.

Preguntas frecuentes

¿Cómo cancelo mi suscripción?
Simplemente, dirígete a la sección ajustes de la cuenta y haz clic en «Cancelar suscripción». Así de sencillo. Después de cancelar tu suscripción, esta permanecerá activa el tiempo restante que hayas pagado. Obtén más información aquí.
¿Cómo descargo los libros?
Por el momento, todos nuestros libros ePub adaptables a dispositivos móviles se pueden descargar a través de la aplicación. La mayor parte de nuestros PDF también se puede descargar y ya estamos trabajando para que el resto también sea descargable. Obtén más información aquí.
¿En qué se diferencian los planes de precios?
Ambos planes te permiten acceder por completo a la biblioteca y a todas las funciones de Perlego. Las únicas diferencias son el precio y el período de suscripción: con el plan anual ahorrarás en torno a un 30 % en comparación con 12 meses de un plan mensual.
¿Qué es Perlego?
Somos un servicio de suscripción de libros de texto en línea que te permite acceder a toda una biblioteca en línea por menos de lo que cuesta un libro al mes. Con más de un millón de libros sobre más de 1000 categorías, ¡tenemos todo lo que necesitas! Obtén más información aquí.
¿Perlego ofrece la función de texto a voz?
Busca el símbolo de lectura en voz alta en tu próximo libro para ver si puedes escucharlo. La herramienta de lectura en voz alta lee el texto en voz alta por ti, resaltando el texto a medida que se lee. Puedes pausarla, acelerarla y ralentizarla. Obtén más información aquí.
¿Es Modern Python Cookbook un PDF/ePUB en línea?
Sí, puedes acceder a Modern Python Cookbook de Steven F. Lott en formato PDF o ePUB, así como a otros libros populares de Computer Science y Programming in Python. Tenemos más de un millón de libros disponibles en nuestro catálogo para que explores.

Información

Año
2020
ISBN
9781800205802
Edición
2

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 setremove(), 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...

Índice