Post

30 cool Python tricks including Slicing, In-place Swap, List vs. Tuple etc

30 cool Python tricks including Slicing, In-place Swap, List vs. Tuple etc

1. Slicing

Access or reverse sequences using sequence[start:stop:step].

a = "Hello World!"
print(a[::-1])  # !dlroW olleH

2. In-place Swap / Simultaneous Assignment

Swap or assign multiple variables in one line.

a, b = 10, 5
a, b = b, a + 2
print(a, b)  # 5 12

3. List vs. Tuple

  • Lists are mutable, tuples are immutable and memory-efficient.
a = [1,2,3]; b = (1,2,3)
a[0] = 9  # allowed
# b[0] = 9  -> TypeError

4. Generators

Lazy evaluation saves memory. Use () instead of [].

gen = (x*2 for x in range(10))
print(next(gen))  # 0

5. Aliasing

Two variables pointing to the same object share changes.

a = [1,2,3]; b = a
b[0] = 9
print(a)  # [9,2,3]

Clone using b = a[:] or list(a) to avoid aliasing.


6. The not Operator

Check if a data structure is empty.

a = []
if not a:
    print("Empty")  # Empty

7. F-strings

Format strings easily:

name, age = "John", 19
print(f"Hi, I'm {name} and I'm {age}")
print(f"{name=}, {age=}")  # Python 3.8+

8. Print end Parameter

Control line endings.

print("Hello", end=" ")  # no newline

9. Append to Tuple

Tuples are immutable but can contain mutable objects.

a = (1,2,[3])
a[2].append(4)
print(a)  # (1,2,[3,4])

10. Merging Dictionaries

a = {"a":1}; b={"b":2}
merged = a | b

11. Ternary Operator

name = "John" if True else "Doe"

12. Remove Duplicates from List

a = [1,1,2,2]
print(list(set(a)))  # [1,2]

13. Standalone Underscore _

Stores the last evaluated result in interactive mode.


14. Underscore to Ignore Values

for _ in range(3):
    print("Ignore index")

15. Trailing Underscores

Avoid conflicts with keywords:

list_ = [1,2,3]

16. Leading Underscores

Indicates internal use:

class A: 
    def __init__(self):
        self._internal = 5

17. Underscore as Visual Separator

num = 1_000_000

18. __name__ == "__main__"

Run code only when script is executed directly.


19. setdefault()

Simpler way to count dictionary occurrences:

counts.setdefault(word,0)
counts[word]+=1

20. Regex Matching

import re
num = re.compile(r"(0)?(\+44)?\d{10}")

21. Regex Pipe |

Matches multiple patterns:

re.search(r"Super(man|woman|human)", text)

22. Print sep Parameter

print(1,2,3, sep=".")  # 1.2.3

23. Lambda Functions

f = lambda x,y: x**y
print(f(4,2))  # 16

24. swapcase()

"AbC".swapcase()  # aBc

25. isalnum()

Check if string contains only letters and numbers.


26. Exception Handling

try: ratio = x/y
except ZeroDivisionError: ratio = x/(y+1)

27. Difference Between Lists

set(list1) ^ set(list2)  # symmetric difference

28. *args & **kwargs

Pass variable number of arguments:

def func(*args, **kwargs): pass

29. Ellipsis ...

Placeholder or multidimensional slicing in NumPy.


30. List Comprehension

Elegant list creation with conditions:

[x for x in range(10) if x%2==0 and x!=0]  # [2,4,6,8]

Unable to operate without login

Comment 0

The list is empty, no content at the moment.