惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

L
LangChain Blog
T
The Blog of Author Tim Ferriss
Stack Overflow Blog
Stack Overflow Blog
博客园 - 司徒正美
云风的 BLOG
云风的 BLOG
The GitHub Blog
The GitHub Blog
A
About on SuperTechFans
Attack and Defense Labs
Attack and Defense Labs
Project Zero
Project Zero
C
Cybersecurity and Infrastructure Security Agency CISA
N
Netflix TechBlog - Medium
P
Privacy International News Feed
爱范儿
爱范儿
V
Vulnerabilities – Threatpost
The Hacker News
The Hacker News
MongoDB | Blog
MongoDB | Blog
Spread Privacy
Spread Privacy
G
Google Developers Blog
Cyberwarzone
Cyberwarzone
L
LINUX DO - 热门话题
C
Cisco Blogs
T
Tor Project blog
NISL@THU
NISL@THU
I
InfoQ
P
Privacy & Cybersecurity Law Blog
Simon Willison's Weblog
Simon Willison's Weblog
D
DataBreaches.Net
有赞技术团队
有赞技术团队
S
Schneier on Security
D
Darknet – Hacking Tools, Hacker News & Cyber Security
月光博客
月光博客
T
The Exploit Database - CXSecurity.com
C
CXSECURITY Database RSS Feed - CXSecurity.com
G
GRAHAM CLULEY
Cisco Talos Blog
Cisco Talos Blog
Recent Announcements
Recent Announcements
The Cloudflare Blog
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
T
Threatpost
B
Blog
Microsoft Security Blog
Microsoft Security Blog
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
H
Help Net Security
美团技术团队
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
Scott Helme
Scott Helme
腾讯CDC
酷 壳 – CoolShell
酷 壳 – CoolShell
Blog — PlanetScale
Blog — PlanetScale
The Register - Security
The Register - Security

Martin Heinz's Blog

A Guide to Python's Weak References Using weakref Module Recent Docker BuildKit Features You're Missing Out On Modern Git Commands and Features You Should Be Using Everything You Can Do with Python's textwrap Module Monitoring Indoor Air Quality with Prometheus, Grafana and a CO2 Sensor Everything You Can Do with Python's bisect Module You Don't Need a Dedicated Cache Service - PostgreSQL as a Cache A Collection of Docker Images To Solve All Your Debugging Needs Weird Python "Features" That Might Catch You By Surprise Lessons Learned From Writing 100 Articles Debugging Crashes and Deadlocks in Python using PyStack Goodbye etcd, Hello PostgreSQL: Running Kubernetes with an SQL Database Remote Interactive Debugging of Python Applications Running in Kubernetes The Right Way to Run Shell Commands From Python Real Multithreading is Coming to Python - Learn How You Can Use It Now Python's Missing Batteries: Essential Libraries You're Missing Out On Kubernetes-Native Synthetic Monitoring with Kuberhealthy Make Your CLI Demos a Breeze with Zero Stress and Zero Mistakes Reduce - The Power of a Single Python Function Why I Will Never Use Alpine Linux Ever Again Cgroups - Deep Dive into Resource Management in Kubernetes Dictionary Dispatch Pattern in Python Boost Your Python Application Performance using Continuous Profiling Lazy Evaluation Using Recursive Python Generators Python Magic Methods You Haven't Heard About Getting Started with Mastodon API in Python Backup-and-Restore of Containers with Kubernetes Checkpointing API Getting Started with Google APIs in Python Python CLI Tricks That Don't Require Any Code Whatsoever All The Ways To Introspect Python Objects at Runtime What is Python's "self" Argument, Anyway? You Should Be Using Python's Walrus Operator - Here's Why Recipes and Tricks for Effective Structural Pattern Matching in Python It's Time to Say Goodbye to These Obsolete Python Libraries Advanced Features of Kubernetes' Horizontal Pod Autoscaler Data and System Visualization Tools That Will Boost Your Productivity Stop Messing with Kubernetes Finalizers Automate All the Boring Kubernetes Operations with Python End-to-End Monitoring with Grafana Cloud with Minimal Effort Bitly | bit.ly/3JLmSgA Bitly | bit.ly/3uETfbi Bitly | bit.ly/3MI4Iz0 Bitly | bit.ly/3M30D82 Bitly | bit.ly/3oMJ6qR Bitly | bit.ly/3IRD7IK Bitly | bit.ly/3A3B69t Bitly | bit.ly/31lKCYA Bitly | bit.ly/30uviIM Bitly | bit.ly/3E1X2mw Bitly | bit.ly/3Dv7JxP Bitly | bit.ly/3GG1BEz Bitly | bit.ly/3lLavs4 Bitly | bit.ly/39TqP3m Bitly | bit.ly/3A5Mpx8 Bitly | bit.ly/3kGwPl4 Bitly | bit.ly/3iHtulU Bitly | bit.ly/3xGjtKS Bitly | bit.ly/3h8DZg0 Bitly | bit.ly/2RQn1dG Bitly | bit.ly/3p2B5wW The Easiest Way to Debug Kubernetes Workloads Bitly | bit.ly/2PHVudx Cloud Native CI/CD with Tekton - Building Custom Tasks Bitly | bit.ly/3dg3QR9 Bitly | bit.ly/3qHtSkZ Deep Dive into Docker Internals - Union Filesystem Bitly | bit.ly/3qlRAUN Bitly | bit.ly/3pCUJ26 Bitly | bit.ly/3ifZxYr Bitly | bit.ly/34ZhIMt Bitly | bit.ly/3qSO7h0 Bitly | bit.ly/3muGLOk Bitly | bit.ly/35xN79v Bitly | bit.ly/3mLGshK Bitly | bit.ly/2IvkGQl Bitly | bit.ly/2Sk1KFK Bitly | bit.ly/3iCNIL6 Bitly | bit.ly/3beQPpy Saving Your Linux Machine from Certain Death New Features in Python 3.9 You Should Know About Deploy Any Python Project to Kubernetes Analyzing Docker Image Security Recursive SQL Queries with PostgreSQL Automating Every Aspect of Your Python Project Tour of Python Itertools Implementing 2D Physics in Javascript Ultimate Setup for Your Next Python Project Making Python Programs Blazingly Fast Security and Cryptography Mistakes You Are Probably Doing All The Time Going Serverless with OpenFaaS and Golang - Building Optimized Templates Going Serverless with OpenFaaS and Golang - The Ultimate Setup and Workflow Setting Up Swagger Docs for Golang API Building RESTful APIs in Golang Pytest Features, That You Need in Your (Testing) Life Setting up GitHub Package Registry with Docker and Golang Ultimate Setup for Your Next Golang Project Python Tips and Trick, You Haven't Already Seen, Part 2. Tricks for Postgres and Docker that will make your life easier Getting The Most Out of Reading Books - Reading The "Professional Way" Python Tips and Trick, You Haven't Already Seen
Python List Comprehensions Are More Powerful Than You Might Think
Martin · 2022-09-06 · via Martin Heinz's Blog

Python's list comprehensions (and generators) are an awesome feature that can greatly simplify your code. Most of the time however, we only use them to write a single for loop, maybe with addition of one if conditional and that's it. If you start poking around a bit though, you will find out that there are many more features of Python's comprehensions that you don't know about, but can learn a lot from...

Multiple Conditionals

We know that we can use if conditional to filter results of a list comprehension and with simple comprehensions single if is usually sufficient. What if you wanted a nested conditional, though?


values = [True, False, True, None, True]
print(['yes' if v is True else 'no' if v is False else 'unknown' for v in values])
# ['yes', 'no', 'yes', 'unknown', 'yes']

# Above is equivalent to:
result = []
for v in values:
    if v is True:
        result.append('yes')
    else:
        if v is False:
            result.append('no')
        else:
            result.append('unknown')

print(result)
# ['yes', 'no', 'yes', 'unknown', 'yes']

It's possible to build a nested conditional using "conditional expressions", or as it's generally called a ternary operator. It's not exactly a pretty solution, so you will have to decide whether the few saved lines are worth the nasty one-liner.

Apart from using complex conditionals, it's also possible to stack multiple ifs in a comprehension:


print([i for i in range(100) if i > 10 if i < 20 if i % 2])
# [11, 13, 15, 17, 19]

# Above is equivalent to:
result = []
for i in range(100):
    if i > 10:
        if i < 20:
            if i % 2:
                result.append(i)

print(result)
# [11, 13, 15, 17, 19]

Looking at the expanded code above, it doesn't really make much sense to write it this way, but the syntax allows it.

One reason why you might want to use it, is for readability purposes:


print([i for i in range(100)
       if i > 10
       if i < 20
       if i % 2])

Avoid Repeated Evaluation

Let's say you have comprehension which calls an expensive function both in the conditional and in the loop body:


def func(val):
    # Expensive computation...
    return val > 4

values = [1, 4, 3, 5, 12, 9, 0]
print([func(x) for x in values if func(x)])  # Inefficient
# [True, True, True]

This is inefficient as it doubles the computation time, but what can we do about it? Nested comprehensions to the rescue!


print([y for y in (func(x) for x in values) if y])  # Efficient
# [True, True, True]

I want to highlight that the above is not a double loop. In this example we build a generator inside list comprehension which is consumed by the outer loop. If you find this hard to read, then alternative would be to use the walrus operator:


print([y for x in values if (y := func(x))])

Here func is called only once, creating a local variable y which can be used in other part of the expression.

Handling Exceptions

Even though list comprehensions are usually used for simple tasks - such as calling a function on each element of the list - there are situations where exception might be thrown inside the comprehension. There's however no native way of handling an exception inside a list comprehension, so what can we do about it?


def catch(f, *args, handle=lambda e: e, **kwargs):
    try:
        return f(*args, **kwargs)
    except Exception as e:
        return handle(e)


values = [1, "text", 2, 5, 1, "also-text"]
print([catch(int, value) for value in values])
print([catch(lambda: int(value)) for value in values])  # Alternative syntax
# [
#   1,
#   ValueError("invalid literal for int() with base 10: 'text'"),
#   2,
#   5,
#   1,
#   ValueError("invalid literal for int() with base 10: 'also-text'")
# ]

We need a handler function to catch an exception inside a comprehension. Here we create a function catch which takes a function and its arguments. If an exception is thrown inside catch, then the exception is returned.

This is not an ideal solution, considering that we need a helper function, but it's the best we can do as the proposal (PEP 463), which tried to introduce a syntax for this, got rejected.

Breaking the Loop

Another limitation of list comprehensions is the inability to break the loop. While not possible natively we can implement a little hack that solves the problem:


print([i for i in iter(iter(range(10)).__next__, 4)])
# [0, 1, 2, 3]

from itertools import takewhile
print([n for n in takewhile(lambda x: x != 4, range(10))])
# [0, 1, 2, 3]

First example above uses a little know feature/behavior of iter function. The iter(callable, sentinel) returns an iterator that "breaks" iteration once callable function value is equal to a sentinel value. When the inner iter returns the sentinel (4 in the example), the loop automatically stops.

This is not very readable, so you can instead take advantage of the great itertools module and the takewhile function as shown in the second example.

As a side note - if you thought that breaking a loop in list comprehensions was possible, then you'd be correct. Until Python 3.5, you could use helper function to raise StopIteration inside list comprehensions, that was however changed with PEP 479.

Tricks (and Hacks)

In the previous sections, we've seen some obscure features of list comprehensions that might or might not be very useful in day-to-day coding. So, let's now take a look at some tricks (and little hacks) that you can put to use right away.

While plain, vanilla list comprehensions are very powerful, they become even better when paired with libraries such itertools (see previous section) or its extension more-itertools.

Let's say you need to find runs of consecutive numbers, dates, letters, booleans or any other orderable objects. You can solve this elegantly by pairing consecutive_groups from more-itertools with a list comprehension:


import datetime
# pip install more-itertools
import more_itertools

dates = [
    datetime.datetime(2020, 1, 15),
    datetime.datetime(2020, 1, 16),
    datetime.datetime(2020, 1, 17),
    datetime.datetime(2020, 2, 1),
    datetime.datetime(2020, 2, 2),
    datetime.datetime(2020, 2, 4)
]

groups = [list(group) for group in more_itertools.consecutive_groups(dates, ordering=lambda d: d.toordinal())]
# [
# [datetime.datetime(2020, 1, 15, 0, 0), datetime.datetime(2020, 1, 16, 0, 0), datetime.datetime(2020, 1, 17, 0, 0)],
# [datetime.datetime(2020, 2, 1, 0, 0), datetime.datetime(2020, 2, 2, 0, 0)],
# [datetime.datetime(2020, 2, 4, 0, 0)]
# ]

Here we have list of dates, some of which are consecutive. We pass the dates to the consecutive_groups function using ordinal values of the dates for ordering. We then collect returned groups into a list using a comprehension.

Computing accumulating sums of numbers is very easy in Python - you can just pass a list to itertools.accumulate and you get back the sums. What if we wanted to undo the accumulation though?


from itertools import accumulate

data = [4, 5, 12, 8, 1, 10, 21]
cumulative = list(accumulate(data, initial=100))
print(cumulative)
# [100, 104, 109, 121, 129, 130, 140, 161]

print([y - x for x, y in more_itertools.pairwise(cumulative)])
# [4, 5, 12, 8, 1, 10, 21]

With help of more_itertools.pairwise it's pretty simple!

As was mentioned earlier, the new-ish walrus operator can be used with list comprehensions to create a local variable. That can be useful in many situations. One such situation is with any() and all() functions:

Python's any() and all() functions can verify whether any or all values in some iterable satisfy certain condition. What if you however want to also capture the value that caused any() to return True (so-called "witness") or the value that caused all() to fail (so-called "counterexample")?


numbers = [1, 4, 6, 2, 12, 4, 15]

# Only returns boolean, not the values
print(any(number > 10 for number in numbers))  # True
print(all(number < 10 for number in numbers))  # False

# ---------------------
any((value := number) > 10 for number in numbers)  # True
print(value)  # 12

all((counter_example := number) < 10 for number in numbers)  # False
print(counter_example)  # 12

Both any() and all() use short-circuiting to evaluate the given expression. This means that they stop the evaluation as soon as they find the first "witness" or "counterexample" respectively. Therefore, with this trick the variable created by walrus operator will always give us the first "witness"/"counterexample".

Closing Thoughts

Many of the features and tricks here are meant to demonstrate possibilities and limits of list comprehensions. Learning these intricacies is - in my opinion - a good way of gaining better understanding of particular language feature, even if it's not really useful in daily coding. On top of that, it's fun.

With that said, I hope you learn something here, and be aware that if you decide to use things like complex conditionals or loop breaks in your list comprehensions, then your coworkers might end-up hating you.