Fundamentals 10 min read

Master Python One‑Liners: 25 Handy Tricks for Variables, Lists & Files

This tutorial presents 25 concise Python one‑liners that demonstrate clever tricks such as swapping variables, multiple assignment, list comprehensions, file I/O, lambda functions, and other useful techniques to write clear and efficient code.

Python Crawling & Data Mining
Python Crawling & Data Mining
Python Crawling & Data Mining
Master Python One‑Liners: 25 Handy Tricks for Variables, Lists & Files

Since writing my first line of Python, I have been fascinated by its simplicity and readability; this article showcases 25 practical one‑line Python tricks that cover variable swapping, multiple assignment, list operations, file handling, lambda functions, and more.

1. Swap two variables

a, b = b, a

2. Multiple variable assignment

a, b, c = 4, 5.5, 'Hello'

3. Sum of even numbers in a list

a = [1, 2, 3, 4, 5, 6]
s = sum(num for num in a if num % 2 == 0)

4. Delete multiple elements from a list

a = [1, 2, 3, 4, 5]
del a[1::2]  # removes elements at odd indices

5. Read a file into a list

lst = [line.strip() for line in open('data.txt')]
print(lst)

6. Write data to a file

with open('data.txt', 'a', newline='
') as f:
    f.write('Python is awesome')

7. Create a list with a range

lst = [i for i in range(10)]
print(lst)

8. Map a list or type‑convert an entire list

list(map(int, ['1', '2', '3']))
list(map(float, [1, 2, 3]))
[float(i) for i in [1, 2, 3]]

9. Create a set

{x**2 for x in range(10) if x % 2 == 0}

10. Fizz Buzz (1‑20)

[ 'FizzBuzz' if i%3==0 and i%5==0 else 'Fizz' if i%3==0 else 'Buzz' if i%5==0 else i for i in range(1,21) ]

11. Palindrome check

text = 'level'
ispalindrome = text == text[::-1]
print(ispalindrome)

12. Convert space‑separated integers to a list

lis = list(map(int, input().split()))
print(lis)

13. Lambda function (square)

sqr = lambda x: x * x
print(sqr(10))

14. Check existence of a number in a list

num = 5
if num in [1,2,3,4,5]:
    print('present')

15. Print a pattern

n = 5
print('
'.join('😀'*i for i in range(1, n+1)))

16. Find factorial

import math
n = 6
print(math.factorial(n))

17. Fibonacci sequence

fibo = [0,1]
[fibo.append(fibo[-2]+fibo[-1]) for _ in range(5)]
print(fibo)

18. Generate primes

list(filter(lambda x: all(x % y != 0 for y in range(2, x)), range(2,13)))

19. Find maximum value

findmax = lambda x, y: x if x > y else y
print(findmax(5, 14))
# or simply max(5, 14)

20. Scale list elements

def scale(lst, x):
    return [i*x for i in lst]
print(scale([2,3,4], 2))

21. Transpose a matrix

a = [[1,2,3],[4,5,6],[7,8,9]]
transpose = [list(i) for i in zip(*a)]
print(transpose)

22. Count occurrences with regex

import re
cnt = len(re.findall('python', 'python is a programming language. python is python'))
print(cnt)

23. Replace text

"python is a programming language. python is python".replace('python', 'Java')

24. Simulate a coin toss

import random
print(random.choice(['Head', 'Tail']))

25. Generate groups (Cartesian product)

groups = [(a,b) for a in ['a','b'] for b in [1,2,3]]
print(groups)
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

LambdaOne-linerdata-structuresfile-iolist-comprehension
Python Crawling & Data Mining
Written by

Python Crawling & Data Mining

Life's short, I code in Python. This channel shares Python web crawling, data mining, analysis, processing, visualization, automated testing, DevOps, big data, AI, cloud computing, machine learning tools, resources, news, technical articles, tutorial videos and learning materials. Join us!

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.