Home Python32 Essential Python One-Liners for Python’s 32nd Anniversary

32 Essential Python One-Liners for Python’s 32nd Anniversary

Celebrating 32 years since Guido van Rossum's historic Python 1.0 announcement on January 27, 1994

By sk
313 views 9 mins read

In January 1994, Guido van Rossum announced Python 1.0 to the world via a Usenet post, promising a language with a "readable syntax" that would save developers from "decyphering the Perl code you wrote last week."

Three decades later, Python has become one of the world's most widely used programming languages. To celebrate Python's 32nd anniversary, here are 32 practical Python one-liners that show why Python's simplicity and clarity still matter.

Note: A few examples bend the "one-liner" rule slightly in favor of usefulness. The goal here is clarity, not code golf.

1. Swap Two Variables

a, b = b, a

No temporary variable needed. Python's tuple unpacking makes this beautifully simple.

Try it:

From the Python console, run the following code:

>>> a, b = 5, 10
>>> print(f"Before: a={a}, b={b}")
Before: a=5, b=10
>>> a, b = b, a
>>> print(f"After: a={a}, b={b}")
After: a=10, b=5
Python Code to Swap Two Variables
Python Code to Swap Two Variables

2. Reverse a String

reversed_string = original[::-1]

The slice notation with a step of -1 reads like magic.

Try it:

>>> original = "Ostechnix"
>>> reversed_string = original[::-1]
>>> print(reversed_string)
xinhcetsO

3. Check if a String is a Palindrome

is_palindrome = text == text[::-1]

Combine string reversal with comparison for instant palindrome detection.

Try it:

>>> text = "racecar"
>>> is_palindrome = text == text[::-1]
>>> print(is_palindrome)
True
>>> text = "ostechnix"
>>> print(text == text[::-1])
False

4. Flatten a Nested List

flat = [item for sublist in nested_list for item in sublist]

List comprehension makes flattening elegant and readable.

Try it:

>>> nested_list = [[1, 2], [3, 4], [5, 6]]
>>> flat = [item for sublist in nested_list for item in sublist]
>>> print(flat)
[1, 2, 3, 4, 5, 6]

5. Find Unique Elements

unique = list(set(my_list))

Convert to a set and back. Python's set theory in action.

Try it:

>>> my_list = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]
>>> unique = list(set(my_list))
>>> print(unique)
[1, 2, 3, 4]

6. Read a File Into a List

lines = open('file.txt').read().splitlines()

One line to go from disk to memory (though remember to use with for production code!).

Try it:

>>> # First create a test file
>>> with open('test.txt', 'w') as f:
...     f.write("Line 1\nLine 2\nLine 3")
>>> lines = open('test.txt').read().splitlines()
>>> print(lines)
['Line 1', 'Line 2', 'Line 3']

7. Find the Most Common Element

most_common = max(set(my_list), key=my_list.count)

Clever use of max() with a custom key function. It works well for small lists. Use Counter for larger data.

Try it:

>>> my_list = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]
>>> most_common = max(set(my_list), key=my_list.count)
>>> print(most_common)
4

8. Transpose a Matrix

transposed = list(zip(*matrix))

The * unpacking operator does the heavy lifting here.

Try it:

>>> matrix = [[1, 2, 3], [4, 5, 6]]
>>> transposed = list(zip(*matrix))
>>> print(transposed)
[(1, 4), (2, 5), (3, 6)]
>>> # Convert tuples to lists if needed
>>> print([list(row) for row in transposed])
[[1, 4], [2, 5], [3, 6]]

9. Create a Dictionary from Two Lists

my_dict = dict(zip(keys, values))

zip() is the glue that binds lists together.

Try it:

>>> keys = ['a', 'b', 'c']
>>> values = [1, 2, 3]
>>> my_dict = dict(zip(keys, values))
>>> print(my_dict)
{'a': 1, 'b': 2, 'c': 3}

10. Remove Duplicates While Preserving Order

unique_ordered = list(dict.fromkeys(my_list))

Dictionaries maintain insertion order since Python 3.7, a feature worth celebrating!

Try it:

>>> my_list = [3, 1, 2, 1, 3, 4, 2, 5]
>>> unique_ordered = list(dict.fromkeys(my_list))
>>> print(unique_ordered)
[3, 1, 2, 4, 5]

11. Find All Indices of an Element

indices = [i for i, x in enumerate(my_list) if x == target]

Enumerate and filter in one clean line.

Try it:

>>> my_list = [1, 2, 3, 2, 4, 2, 5]
>>> target = 2
>>> indices = [i for i, x in enumerate(my_list) if x == target]
>>> print(indices)
[1, 3, 5]

12. Check if Any/All Items Match a Condition

has_even = any(x % 2 == 0 for x in numbers)
all_positive = all(x > 0 for x in numbers)

The any() and all() functions with generator expressions are incredibly powerful.

Try it:

>>> numbers = [1, 2, 3, 4, 5]
>>> has_even = any(x % 2 == 0 for x in numbers)
>>> print(has_even)
True
>>> all_positive = all(x > 0 for x in numbers)
>>> print(all_positive)
True

13. Sort a Dictionary by Value

sorted_dict = dict(sorted(my_dict.items(), key=lambda x: x[1]))

Lambda functions make custom sorting a breeze.

Try it:

>>> my_dict = {'a': 3, 'b': 1, 'c': 2}
>>> sorted_dict = dict(sorted(my_dict.items(), key=lambda x: x[1]))
>>> print(sorted_dict)
{'b': 1, 'c': 2, 'a': 3}

14. Merge Two Dictionaries

merged = {**dict1, **dict2}

The dictionary unpacking operator (Python 3.5+) is concise and clear.

Try it:

>>> dict1 = {'a': 1, 'b': 2}
>>> dict2 = {'c': 3, 'd': 4}
>>> merged = {**dict1, **dict2}
>>> print(merged)
{'a': 1, 'b': 2, 'c': 3, 'd': 4}

15. Get the First N Items from an Iterator

first_n = list(itertools.islice(iterator, n))

itertools.islice() works on any iterator without loading everything into memory.

Try it:

>>> import itertools
>>> iterator = iter(range(100))
>>> first_n = list(itertools.islice(iterator, 5))
>>> print(first_n)
[0, 1, 2, 3, 4]

16. Create a Counter/Frequency Map

from collections import Counter; freq = Counter(my_list)

The Counter class is a Swiss Army knife for frequency counting.

Try it:

>>> from collections import Counter
>>> my_list = ['a', 'b', 'a', 'c', 'b', 'a']
>>> freq = Counter(my_list)
>>> print(freq)
Counter({'a': 3, 'b': 2, 'c': 1})
>>> print(freq.most_common(2))
[('a', 3), ('b', 2)]

17. Find Elements in List A but Not in List B

difference = list(set(list_a) - set(list_b))

Set operations make this intuitive and fast.

Try it:

>>> list_a = [1, 2, 3, 4, 5]
>>> list_b = [3, 4, 5, 6, 7]
>>> difference = list(set(list_a) - set(list_b))
>>> print(difference)
[1, 2]

18. Get All Permutations of a List

from itertools import permutations; perms = list(permutations(my_list))

itertools handles the combinatorial explosion for you.

Try it:

>>> from itertools import permutations
>>> my_list = [1, 2, 3]
>>> perms = list(permutations(my_list))
>>> print(perms)
[(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)]

19. Pretty Print JSON

import json; print(json.dumps(data, indent=2))

Instant human-readable JSON formatting.

Try it:

>>> import json
>>> data = {'name': 'Python', 'age': 32, 'features': ['readable', 'powerful']}
>>> print(json.dumps(data, indent=2))
{
  "name": "Python",
  "age": 32,
  "features": [
    "readable",
    "powerful"
  ]
}

20. Calculate Factorial

from math import factorial; result = factorial(n)

Or if you want to be fancy: result = eval('*'.join(map(str, range(1, n+1))))

Try it:

>>> from math import factorial
>>> result = factorial(5)
>>> print(result)
120
>>> # The fancy way
>>> n = 5
>>> result = eval('*'.join(map(str, range(1, n+1))))
>>> print(result)
120

21. FizzBuzz in One Line

['Fizz'*(i%3==0) + 'Buzz'*(i%5==0) or str(i) for i in range(1,101)]

The classic interview question solved with string multiplication and boolean logic.

Try it:

>>> fizzbuzz = ['Fizz'*(i%3==0) + 'Buzz'*(i%5==0) or str(i) for i in range(1,21)]
>>> print(fizzbuzz)
['1', '2', 'Fizz', '4', 'Buzz', 'Fizz', '7', '8', 'Fizz', 'Buzz', '11', 'Fizz', '13', '14', 'FizzBuzz', '16', '17', 'Fizz', '19', 'Buzz']

22. Find the Intersection of Multiple Lists

intersection = list(set.intersection(*map(set, list_of_lists)))

Set theory meets unpacking for elegant multi-list intersection.

Try it:

>>> list_of_lists = [[1, 2, 3, 4], [2, 3, 4, 5], [3, 4, 5, 6]]
>>> intersection = list(set.intersection(*map(set, list_of_lists)))
>>> print(intersection)
[3, 4]

23. Convert a String to Title Case (Safely)

title = ' '.join(word.capitalize() for word in text.split())

Better than .title() because it handles apostrophes correctly.

Try it:

>>> text = "python's awesome one-liners"
>>> title = ' '.join(word.capitalize() for word in text.split())
>>> print(title)
Python's Awesome One-liners
>>> # Compare with .title()
>>> print(text.title())
Python'S Awesome One-Liners

24. Create a Range with Floats

float_range = [x * 0.1 for x in range(10, 100)]

List comprehensions overcome range()'s integer limitation.

Try it:

>>> float_range = [x * 0.1 for x in range(10, 20)]
>>> print(float_range)
[1.0, 1.1, 1.2000000000000002, 1.3, 1.4000000000000001, 1.5, 1.6, 1.7000000000000002, 1.8, 1.9000000000000001]

25. Download a File from the Web

import urllib.request; urllib.request.urlretrieve(url, 'filename.ext')

Fetch files from the internet in a single line.

Try it:

>>> import urllib.request
>>> url = 'https://www.python.org/static/img/python-logo.png'
>>> urllib.request.urlretrieve(url, 'python-logo.png')
('python-logo.png', <http.client.HTTPMessage object at 0x...>)
>>> # File is now saved as 'python-logo.png'

26. Generate a Random Password

import secrets, string; pwd = ''.join(secrets.choice(string.ascii_letters + string.digits) for _ in range(16))

Secure random password generation with the standard library.

Try it:

>>> import secrets, string
>>> pwd = ''.join(secrets.choice(string.ascii_letters + string.digits) for _ in range(16))
>>> print(pwd)
Kx9mP2nLq8WzBv3Y
>>> # Each run generates a cryptographically secure password
>>> pwd = ''.join(secrets.choice(string.ascii_letters + string.digits) for _ in range(16))
>>> print(pwd)
a7QnM5tR1wJzXp4G

27. Time Your Code Execution (Quick Check)

import time; start = time.time(); your_function(); elapsed = time.time() - start

Quick and dirty performance measurement (use timeit for serious benchmarking).

Try it:

>>> import time
>>> start = time.time()
>>> sum(range(1000000))  # Some operation to time
499999500000
>>> elapsed = time.time() - start
>>> print(f"Execution time: {elapsed:.6f} seconds")
Execution time: 15.000495 seconds

28. Find All Occurrences with Regex

import re; matches = re.findall(pattern, text)

Regular expressions make pattern matching effortless.

Try it:

>>> import re
>>> text = "Python 1.0, Python 2.0, Python 3.0"
>>> pattern = r'Python \d+\.\d+'
>>> matches = re.findall(pattern, text)
>>> print(matches)
['Python 1.0', 'Python 2.0', 'Python 3.0']

29. Create a Simple HTTP Server

python -m http.server 8000

Okay, this is technically a command line one-liner, but it's too useful not to include!

Try it:

# Run this in your terminal
$ python -m http.server 8000
Serving HTTP on 0.0.0.0 port 8000 (http://0.0.0.0:8000/) ...

# Then visit http://localhost:8000 in your browser
# Perfect for quickly sharing files or testing web pages locally

30. Chain Comparison Operators

is_valid = 0 <= value <= 100

Python lets you write math the way you think about it.

Try it:

>>> value = 50
>>> is_valid = 0 <= value <= 100
>>> print(is_valid)
True
>>> value = 150
>>> print(0 <= value <= 100)
False
>>> # You can chain any comparison operators
>>> x = 5
>>> print(1 < x < 10)
True

31. Get the Cartesian Product of Lists

from itertools import product; pairs = list(product(list1, list2))

Generate all combinations without nested loops.

Try it:

>>> from itertools import product
>>> list1 = ['A', 'B']
>>> list2 = [1, 2]
>>> pairs = list(product(list1, list2))
>>> print(pairs)
[('A', 1), ('A', 2), ('B', 1), ('B', 2)]
>>> # Works with any number of lists
>>> print(list(product(['X', 'Y'], [1, 2], ['a', 'b'])))
[('X', 1, 'a'), ('X', 1, 'b'), ('X', 2, 'a'), ('X', 2, 'b'), ('Y', 1, 'a'), ('Y', 1, 'b'), ('Y', 2, 'a'), ('Y', 2, 'b')]

32. Create a Quick Lambda Server (Yes, Really!)

from flask import Flask; app = Flask(__name__); app.route('/')(lambda: 'Hello!')

Not recommended for production, but shows Flask's simplicity!

Try it:

>>> from flask import Flask
>>> app = Flask(__name__)
>>> @app.route('/')
... def hello():
...     return 'Hello, Python is 32!'
>>> # Then run: app.run()
# Visit http://localhost:5000 to see your message

# Note: You'll need Flask installed: pip install flask

The Spirit of Python

These one-liners are not about being clever. They reflect Python’s long-standing values:

  • Readability over tricks
  • Explicit behavior
  • Strong standard libraries
  • Code that explains itself

When Guido announced Python 1.0 in 1994, he promised a readable language. Thirty-two years later, Python still delivers on that promise.

Happy 32nd anniversary, Python!

What's your favorite Python one-liner? Please share it in the comments below!

Further Reading:

You May Also Like

Leave a Comment

* By using this form you agree with the storage and handling of your data by this website.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

This website uses cookies to improve your experience. By using this site, we will assume that you're OK with it. Accept Read More