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

Deleting from a list of mappings


Removing items from a list has an interesting consequence. Specifically, when item list[x] is removed, one of two other things will happen:

  • Item list[x+1] takes the place of list[x]
  • Item x+1 == len(list) takes the place of list[x] because x was the last index in the list

These are side-effects that happen in addition to removing an item. Because things can move around in a list, it makes deleting more than one item at a time challenging.

When the list contains items that have a definition for the __eq__() special method, then the list remove() method can remove each item. When the list items don't have a simple __eq__() test, then it becomes more challenging to remove multiple items from the list.

How can we delete multiple items from a list?

Getting ready

We'll work with a list-of-dict structure. In this case, we've got some data that includes a song name, the writers, and a duration. The data looks like this:

>>> source = [ 
...    {'title': 'Eruption...