Python is famous for its readability, but sometimes the most mind-blowing thing is how much you can do in just one line of code. Here are 10 Python one-liners that will amaze you.
1. Reverse a string
print("hello world"[::-1])2. Swap two variables without a temp variable
a, b = 5, 10; a, b = b, a3. Check if a string is a palindrome
print(s == s[::-1])4. Find the factorial of a number
import math; print(math.factorial(5))5. Get unique elements from a list
print(list(set([1,2,2,3,4,4,5])))6. Flatten a list of lists
print([x for row in [[1,2],[3,4],[5]] for x in row])7. Generate a Fibonacci sequence (first 10 numbers)
fib = lambda n: n if n<2 else fib(n-1)+fib(n-2); print([fib(i) for i in range(10)])8. Transpose a matrix
print(list(zip(*[[1,2,3],[4,5,6],[7,8,9]])))9. Find the most frequent element in a list
print(max(set([1,2,2,3,3,3,4]), key=[1,2,2,3,3,3,4].count))10. One-line list comprehension for squares
print([x**2 for x in range(10)]) 
No comments:
Post a Comment