Sitemap

Pythonic AF

Join our smart community of Python developers! This is your no-BS guide to mastering Python, deep dives, hot takes, clean code, dirty bugs, and everything in between. From automation to APIs, web apps to AI, we cover real world tips, performance tricks, and more.

10 Python one liners you’ll actually use

Tiny Python tricks that are useful, readable, and not just there to impress people on LinkedIn

5 min read4 days ago

1

There’s a category of Python content that’s basically just language gymnastics.

Stuff that technically works, but turns a five second task into some unreadable one-liner that nobody on your team wants to touch later.

A lot of “Python tricks” fall into that category.

Still, some one liners are genuinely useful. Not because they’re clever.

Mostly because they remove repetitive code you were going to write anyway.

These are the ones I actually see people use repeatedly.

Read the full story for free here on Medium

Press enter or click to view image in full size
Canva

1. Flattening nested lists

flattened = [item for sublist in nested for item in sublist]

This is one of those lines that looks weird for about ten seconds and then becomes completely normal.

You’re basically looping through each sublist, then each item inside it, and building a new flat list.

matrix = [[1, 2], [3, 4], [5, 6]]
flattened = [item for sublist in matrix for item in sublist]…

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web
Already have an account? Sign in

1

Pythonic AF

Published in Pythonic AF

Join our smart community of Python developers! This is your no-BS guide to mastering Python, deep dives, hot takes, clean code, dirty bugs, and everything in between. From automation to APIs, web apps to AI, we cover real world tips, performance tricks, and more.

Aysha R

Written by Aysha R

Python Monster 👑 | 8 years | Solving complex problems, optimizing performance & sharing knowledge | Writer | Coffee, coding & creating every day!

Responses (2)

Unknown user

Write a response

this was seriously eye opening...

For the first one (flattening a list of lists) you can use `sum(my_list, [])` which is much simpler and cleaner. The only downside is that this only works with an iterable of lists (you can use a similar approach for an iterable of tuples). Your approach works for any iterable of iterables.