In the middle of the desert you can say anything you want

18 May 2020

Day 504

Python generator expressions are a thing

How to Use Generators and yield in Python – Real Python:

>>> nums_squared_lc = [num**2 for num in range(5)]
>>> nums_squared_gc = (num**2 for num in range(5))

The second one is a generator expression, with all the nice memory thingsies that entails.

In general How to Stand Out in a Python Coding Interview – Real Python has some very interesting bits I had no idea about.

And from “Dive into python”, p.193:

Using a generator expression instead of a list comprehension can save both RAM and CPU. If you’re building an list just to throw it away (e.g. passing it to tuple() or set()), use a generator expression instead!

Generator expressions are functionally equivalent to generator functions.

Python itertools

The itertools module has a lot of awesome stuff! 1

cycle, count, repeat, etc etc etc.

Scary to think how many hours of coding I could have done over my lifetime if I hadn’t read this.

#!/usr/bin/env python and the env trick for running stuff

From the Learning Python 5th Edition book, Chapter 3 page 60:

#!/usr/bin/env python
...script goes here...

This is fascinating. The env $whatever command returns the location of $whatever, which may or may not be standard. And apparently this is the way to write trueъ portable scripts.

This goes to show that reading some nice reference line-by-line is actually a good thing if you have basic random bits of knowledge about something.

So currently:

  • Finish Diving into Python, at least the parts I feel are relevant If I decide I need more Python in my life,
  • Learning Python 5th edition, 1594 pages, focuses on the Python language which is the official prerequisite to…
  • Programming Python, 1628 pages. It focuses on libraries and tools.

The latter two have actual “Test your knowledge” tests and exercises.

All of them may or may not be helpfully available illegally online, especially on github, especially in a repo I cloned.

  1. 9.7. itertools — Functions creating iterators for efficient looping — Python 2.7.18 documentation ↩︎

Nel mezzo del deserto posso dire tutto quello che voglio.