Basic Operations and Tricks in Python

Python Tricks and Best Practices

Reading Data From stdin

Python 3 - Read all input at once

import sys

# Read all data as a string
data = sys.stdin.read()
# Split into a list of strings
data = data.split()
# Press Ctrl+D (Linux/Mac) or Ctrl+Z (Windows) to complete input

Python 3 - Read line by line

import sys

# Read single line
line = sys.stdin.readline().strip()

# Read multiple lines
for line in sys.stdin:
    process(line.strip())

Reading structured input

# Read two integers from first line
n_tables, n_queries = map(int, input().split())
# Read a list of integers from second line
counts = list(map(int, input().split()))

Reading Data in Bash Shell

# Redirect file to stdin
python3 main.py < tests/test.txt

# Pipe data to stdin
echo "1 2 3" | python3 main.py

# Here document
python3 main.py << EOF
1 2 3
4 5 6
EOF

Creating Lists of Numbers

n = 10

# Initialize all values to the same number (1D only)
# WARNING: Don't use this for 2D arrays - use list comprehension or numpy
l1 = [1] * n
# Result: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]

# Create sequence of numbers
l2 = list(range(n))
# Result: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

# Range with start and step
l3 = list(range(1, 11, 2))
# Result: [1, 3, 5, 7, 9]

# Create 2D array (correct way)
rows, cols = 3, 4
matrix = [[0] * cols for _ in range(rows)]

# Using numpy for 2D arrays
import numpy as np
matrix = np.zeros((3, 4))

Floor Division (Integer Division)

# Floor division rounds down to nearest integer
# Examples:
# floor(2.4) = 2
# floor(2.8) = 2
# floor(-2.4) = -3  # Note: rounds toward negative infinity

# Floor division in Python using //
3 // 2   # Result: 1
4 // 2   # Result: 2
5 // 2   # Result: 2
-7 // 2  # Result: -4

# Regular division
5 / 2    # Result: 2.5

# Using math.floor()
import math
math.floor(2.8)  # Result: 2

Swapping Values of Two Variables

a = 1
b = 2

# Pythonic way (single line)
a, b = b, a
# Result: a = 2, b = 1

# Multiple variable swap
x, y, z = 1, 2, 3
x, y, z = z, y, x
# Result: x = 3, y = 2, z = 1

Line Continuation (Breaking Long Lines)

# Using backslash
a = 1 + \
    1

a = dostuff(blahblah1, blahblah2, blahblah3, 
            blahblah4, blahblah5, blahblah6, 
            blahblah7)

# Conditional statements
if a == True and \
   b == False:
    pass

# String concatenation
a = '1' + '2' + '3' + \
    '4' + '5'

# Using parentheses (preferred - no backslash needed)
a = ('1' + '2' + '3' +
     '4' + '5')

# Long function calls
result = function_name(
    argument1,
    argument2,
    argument3,
    argument4
)

# Lists and dictionaries (no continuation needed)
my_list = [
    1, 2, 3,
    4, 5, 6
]

my_dict = {
    'key1': 'value1',
    'key2': 'value2'
}

Quick Debugging with pdb

# Insert breakpoint
import pdb; pdb.set_trace()

# Python 3.7+ built-in breakpoint
breakpoint()  # Preferred method

# Common pdb commands:
# n (next)      - Execute next line
# s (step)      - Step into function
# c (continue)  - Continue execution
# l (list)      - Show current code
# p var         - Print variable value
# pp var        - Pretty print variable
# w (where)     - Show stack trace
# u (up)        - Move up in stack
# d (down)      - Move down in stack
# b n           - Set breakpoint at line n
# cl            - Clear breakpoints
# q (quit)      - Exit debugger

# Example usage
def buggy_function(x):
    breakpoint()  # Execution pauses here
    result = x * 2
    return result

Additional Useful Operations

List Comprehensions

# Create list with condition
squares = [x**2 for x in range(10)]
evens = [x for x in range(10) if x % 2 == 0]

# Nested comprehension
matrix = [[i*j for j in range(3)] for i in range(3)]

String Operations

# String formatting
name = "Python"
version = 3.9
print(f"{name} version {version}")  # f-strings (Python 3.6+)
print("{} version {}".format(name, version))  # format method

# Multi-line strings
text = """
This is a
multi-line string
"""

Dictionary Operations

# Get with default value
d = {'a': 1}
value = d.get('b', 0)  # Returns 0 if 'b' doesn't exist

# Dictionary comprehension
squares_dict = {x: x**2 for x in range(5)}

Enumerate and Zip

# Enumerate - get index and value
for i, value in enumerate(['a', 'b', 'c']):
    print(f"{i}: {value}")

# Zip - combine lists
names = ['Alice', 'Bob']
ages = [25, 30]
for name, age in zip(names, ages):
    print(f"{name} is {age} years old")