0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Python Tricks

0
Last updated at Posted at 2026-06-11

1. Dictionary Merge

What is the output?

a = {"x": 1, "y": 2}
b = {"y": 3, "z": 4}
c = a | b
print(c)

a | b keeps overlapping keys from b.

{'x': 1, 'y': 3, 'z': 4}

2. File I/O Modes

Which mode allows reading and writing without truncating the file?
"r+" = read/write without truncation.
"w+" truncates.

"r+"

3. Function Defaults

What is printed?

def f(x, lst=[]):
    lst.append(x)
    return lst

print(f(1))
print(f(2))

Because the default list is shared across calls.

[1]
[1, 2]

4. Tuple Unpacking

Which line fails?

A. a, b = (1, 2)  
B. a, *b = (1, 2, 3)  
C. *a, b = (1, 2, 3)  
D. a, b, c, d = (1, 2, 3)

Answer:

a, b, c, d = (1, 2, 3)

→ Not enough values → ValueError.

5. Module Import Behavior

What happens when a module is imported twice?
Modules execute once and are cached in sys.modules.

6. Regex Greediness

re.findall(r"<.*>", "<a><b><c>")

.* is greedy → matches the entire <a><b><c>.

['<a>', '<b>', '<c>']  

7. Class Method Resolution

class A:
    def f(self): return "A"

class B(A):
    def f(self): return "B"

class C(A):
    pass

class D(B, C):
    pass

print(D().f())

D inherits from B first, so B.f() wins.

B

8. Control Flow

What is printed?

for i in range(3):
    if i == 1:
        continue
    print(i)

i == 1 is skipped.

0
2

9. Exception Propagation

Which block always executes?
finally always executes.

10. List Comprehension Scope

x = 10
lst = [x for x in range(3)]
print(x)

List comprehension has its own scope in Python 3.
x outside remains unchanged.

10

11. String Formatting

Which is valid?
A. f"{1+2}"
B. f"{'a' * 3}"
C. f"{x=}"
D. All of the above
All are valid f‑strings.

12. Async/Await

Which is true about async def?
async def returns a coroutine object.

13. Mutable default traps

def g(a, b=set()):
    b.add(a)
    return b

print(g(1))
print(g(2))
print(g(1))
{1}
{1, 2}
{1, 2}

Because the default set() is shared across all calls.

15. Regex lookaheads

import re
re.findall(r"\b\w+(?=\.)", "end. send. blend test")

(?=.) matches words followed by a dot, but does not consume the dot.
Matches: end, send, blend.

16. Class variable vs instance variable

class A:
    x = []

a1 = A()
a2 = A()

a1.x.append(1)
print(a2.x)

x is a class variable, so both instances share the same list.

[1]

17. Operator precedence

print(2 ** 3 ** 2)

** is right‑associative:
2 ** (3 ** 2) → 2 ** 9 → 512.

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?