Python One-Liners - Write Concise, Eloquent Python Like a Professional
Return to Python Bibliography
Fair Use Commentary Text of Python One-Liners - Write Concise, Eloquent Python Like a Professional
PYTHON ONE-LINERS
Write Concise, Eloquent Python Like a Professional
by Christian Mayer
San Francisco
PYTHON ONE-LINERS. Copyright © 2020 by Christian Mayer.
All rights reserved. No part of this work may be reproduced or transmitted in any form or by any means, electronic or mechanical, including photocopying, recording, or by any information storage or retrieval system, without the prior written permission of the copyright owner and the publisher.
ISBN-10: 1-7185-0050-5
ISBN-13: 978-1-7185-0050-1
Publisher: William Pollock
Production Editors: Janelle Ludowise and Kassie Andreadis
Cover Illustration: Rob Gale
Interior Design: Octopod Studios
Developmental Editors: Liz Chadwick and Alex Freed
Technical Reviewer: Daniel Zingaro
Copyeditor: Sharon Wilkey
Compositor: Danielle Foster
Proofreader: James Fraleigh
Indexer: JoAnne Burek
For information on distribution, translations, or bulk sales, please contact No Starch Press, Inc. directly:
No Starch Press, Inc.
245 8th Street, San Francisco, CA 94103
phone: 1.415.863.9900; info@nostarch.com
The Library of Congress issued the following Cataloging-in-Publication Data for the first edition:
Names: Mayer, Christian (Computer Scientist), author.
Title: Python one-liners: write concise, eloquent Python like a professional / Christian Mayer.
Description: San Francisco : No Starch Press, Inc., 2020. ]] | LCCN 2020001449 (print) | LCCN 2020001450 (ebook) | ISBN 9781718500501 | LCC QA76.73.P98 M39 2020 (print) | LCC QA76.73.P98 (ebook) | Algorithms Afterword Index CONTENTS IN DETAIL ACKNOWLEDGMENTS INTRODUCTION Python One-Liner Example A Note on Readability Who Is This Book For) + [l[0]] + q([x for x in l if x > l[0]]) if l else []
This one-liner is a beautiful and concise way of compressing the famous Quicksort algorithm, though the meaning may be difficult to grasp for many Python beginners and intermediates.
Python one-liners often build on each other, so one-liners will increase in complexity throughout the book. In this book, we’ll start with simple one-liners that will become the basis for more-complex one-liners later. For example, the preceding Quicksort one-liner is difficult and long, based on the easier concept of list comprehension ➊. Here’s a simpler list comprehension that creates a list of squared numbers:
lst = [x**2 for x in range(10)]
We can break this one-liner into even simpler one-liners that teach important Python basics, such as variable assignments, math operators, data structures, for loops, membership operators, and the range() function—all of which happens in a single line of Python!
Know that basic doesn’t mean trivial. All the one-liners we’ll look at are useful, and each chapter addresses a separate area or discipline in computer science, giving you a broad perspective on the power of Python.
A Note on Readability
The Zen of Python comprises 19 guiding principles for the Python programming languages. You can read it in your Python shell by entering import this:
import this
The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
–snip–
According to The Zen of Python, “Readability counts.” One-liners are minimalistic programs to solve problems. In many cases, rewriting a piece of code as a Python one-liner will improve readability and make the code more Pythonic. An example is using list comprehension to reduce the creation of lists into a single line of code. Have a look at the following example:
- BEFORE
squares = []
for i in range(10):
squares.append(i**2)
print(squares)
- [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
In this code snippet, we need five lines of code to create a list of the first 10 square numbers and print it to the shell. However, it’s much better to use a one-liner solution that accomplishes the same thing in a more readable and concise way:
- AFTER
print([i**2 for i in range(10)])
- [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
The output is the same, but the one-liner builds on the more Pythonic concept of list comprehension. It’s easier to read and more concise.
However, Python one-liners can also be hard to understand. In some cases, writing a solution as a Python one-liner isn’t more readable. But just as the chess master must know all possible moves before deciding which one is best, you must know all ways of expressing your thoughts in code so that you can decide on the best one. Going for the most beautiful solution is not a low-priority matter; it’s at the core of the Python ecosystem. As The Zen of Python teaches, “Beautiful is better than ugly.”
Who Is This Book For?
Are you a beginner- to intermediate-level Python coder? Like many of your peers, you may be stuck in your coding progress. This book can help you out. You’ve read a lot of programming tutorials online. You’ve written your own source code and successfully shipped small projects. You’ve finished a basic programming course and read a programming textbook or two. Maybe you’ve even finished a technical program in college, where you’ve learned about the basics of computer science and programming.
Perhaps you’re limited by certain beliefs, like that most coders understand source code much faster than you, or that you’re nowhere near the top 10 percent of programmers. If you want to reach an advanced coding level and join the top coding experts, you need to learn new applicable skills.
I can relate because when I started out studying computer science 10 years ago, I struggled with the belief that I knew nothing about coding. At the same time, it seemed that all my peers were already very experienced and proficient.
In this book, I want to help you overcome these limiting beliefs and push you one step further toward Python mastery.
What Will You Learn?
Here is an overview of what you will learn.
Chapter 1: Python Refresher Introduces the very basics of Python to refresh your knowledge.
Chapter 2: Python Tricks Contains 10 one-liner tricks to help you master the basics, such as list comprehension, file input, the functions lambda, map(), and zip(), the all() quantifier, slicing, and basic list arithmetic. You’ll also learn how to use, manipulate, and leverage data structures to solve various day-to-day problems.
Chapter 3: Data Science Contains 10 one-liners for data science, building on the NumPy library. NumPy is at the heart of Python’s powerful machine learning and data science capabilities. You’ll learn elementary NumPy basics such as array, shape, axis, type, broadcasting, advanced indexing, slicing, sorting, searching, aggregating, and statistics.
Chapter 4: Machine Learning Covers 10 one-liners for machine learning with Python’s scikit-learn library. You’ll learn about regression algorithms that predict values. Examples of these include linear regression, K-Nearest Neighbors, and neural networks. You’ll also learn classification algorithms such as logistic regression, decision-tree learning, support-vector machines, and random forests. Furthermore, you’ll learn about how to calculate basic statistics of multidimensional data arrays, and the K-Means algorithm for unsupervised learning. These algorithms and methods are among the most important algorithms in the field of machine learning.
Chapter 5: Regular Expressions Contains 10 one-liners to help you achieve more with regular expressions. You’ll learn about various basic regular expressions that you can combine (and recombine) in order to create more-advanced regular expressions, using grouping and named groups, negative lookaheads, escaped characters, whitespaces, character sets (and negative characters sets), and greedy/nongreedy operators.
Chapter 6: Algorithms Contains 10 one-liner algorithms addressing a wide range of computer science topics, including anagrams, palindromes, supersets, permutations, factorials, prime numbers, Fibonacci numbers, obfuscation, searching, and algorithmic sorting. Many of these form the basis of more-advanced algorithms and contain the seeds of a thorough algorithmic education.
Afterword Concludes this book and releases you into the real world, packed with your new and improved Python coding skills.
Online Resources
To enhance the training material in this book, I’ve added supplementary resources that you can find online at https://pythononeliners.com/ or http://www.nostarch.com/pythononeliners/. The interactive resources include the following:
Python cheat sheets You can download those Python cheat sheets as printable PDFs and pin them to your wall. The cheat sheets contain essential Python language features, and if you study them thoroughly, you can refresh your Python skills and ensure that you’ve closed any knowledge gap you may have.
One-liner video lessons As part of my Python email course, I’ve recorded many Python one-liner lessons from this book, which you can access for free. Those lessons can assist you in your learning and provide a multimedia learning experience.
Python puzzles You can visit the online resources to solve Python puzzles and use the Finxter.com app for free to test and train your Python skills and measure your learning progress as you go through the book.
Code files and Jupyter notebooks You must roll up your sleeves and start working with code to make progress toward Python mastery. Take your time to play around with various parameter values and input data. For your convenience, I’ve added all Python one-liners as executable code files.