101 Python One-Liners to Impress Your Friends and Colleagues

LEARN TO CODE
8 min read5 days ago

Python is renowned for its simplicity and readability, but it’s also incredibly powerful when it comes to writing concise, expressive code. One-liners in Python can solve complex problems, perform tasks, and manipulate data with brevity and elegance. Here are 101 Python one-liners that will not only impress your friends and colleagues but also make you a more proficient Python programmer.

1. Swap Two Variables

a, b = b, a

2. Reverse a String

reversed_string = 'hello world'[::-1]

3. Check if a String is a Palindrome

is_palindrome = lambda s: s == s[::-1]

4. Find the Factorial of a Number

import math; factorial = math.factorial(5)

5. Create a List of Squares

squares = [x**2 for x in range(10)]

6. Flatten a List of Lists

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

7. Get the Transpose of a Matrix

transpose = list(zip(*[[1, 2, 3], [4, 5, 6], [7, 8, 9]]))

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

LEARN TO CODE

Welcome to Learn To Code! We are dedicated to helping you become a proficient coder, whether you're a complete beginner or looking to advance your skills.