n and Naming Conventions
Python does not use declaration keywords like let, const, or var. Variables are assigned dynamically. The standard naming convention is snake_case for variables and functions, contrasting with JavaScript's camelCase.
# JavaScript: const transactionId = "TX-8842";
transaction_id = "TX-8842"
is_processed = False
retry_count = 3
# Scope control keywords exist but are rarely needed in standard functions.
# 'global' modifies the module-level scope; 'nonlocal' modifies the enclosing function scope.
2. Collections: Lists, Slicing, and Comprehensions
Python lists correspond to JavaScript arrays. However, Python provides powerful slicing syntax that replaces methods like .slice() and .splice(). Slicing creates a shallow copy and never mutates the original list.
payload_ids = [101, 102, 103, 104, 105]
# JavaScript: payloadIds.slice(1, 3)
subset = payload_ids[1:3] # Result: [102, 103]
# Omitting bounds
first_two = payload_ids[:2] # Starts at index 0
last_three = payload_ids[-3:] # Ends at last index
# Slice assignment replaces elements (similar to .splice)
payload_ids[1:2] = [200, 201] # Result: [101, 200, 201, 103, 104, 105]
For transformations, Python favors list comprehensions over chained .map() and .filter() calls. This syntax is more readable and executes faster.
# JavaScript: users.filter(u => u.active).map(u => u.id)
active_user_ids = [
user.id
for user in user_batch
if user.is_active
]
3. Dictionaries and Safe Access
Dictionaries replace JavaScript objects for key-value storage. Keys must be quoted strings. Dot notation is not supported; use bracket notation or the .get() method to avoid KeyError exceptions.
config = {"timeout": 5000, "retries": 3}
# JavaScript: config.timeout
timeout_val = config["timeout"]
# Safe access with default fallback
# JavaScript: config.maxConnections || 10
max_conn = config.get("max_connections", 10)
# Iteration
for key, value in config.items():
print(f"Setting {key}: {value}")
4. Tuples and Unpacking
Tuples are immutable sequences defined by parentheses. They are memory-efficient and hashable, making them suitable for fixed data structures or dictionary keys. Python supports elegant unpacking syntax.
coordinates = (40.7128, -74.0060)
# JavaScript: const [lat, lon] = coordinates;
lat, lon = coordinates
# Extended unpacking with asterisk
data_stream = (10, 20, 30, 40, 50)
start, *middle, end = data_stream
# start=10, middle=[20, 30, 40], end=50
5. Control Flow and Functions
Python uses elif instead of else if. Logical operators are keywords (and, or, not) rather than symbols. Functions are defined with def, and classes use self to reference instance attributes.
def process_request(request_data):
if request_data.method == "POST" and request_data.body:
return handle_create(request_data)
elif request_data.method == "GET":
return handle_read(request_data)
else:
return error_response()
# Class definition
class DataPipeline:
def __init__(self, source_url):
self.source_url = source_url
self.cache = {}
def fetch(self):
# 'self' is required for instance methods
return self.cache.get(self.source_url)
@staticmethod
def validate_format(data):
# Static methods do not take 'self'
return isinstance(data, dict)
6. Functional Patterns and Lazy Evaluation
Global functions map() and filter() replace array methods. Crucially, these return iterator objects, not lists. This enables lazy evaluation, saving memory for large datasets. You must wrap the result in list() if a concrete list is required.
values = [1, 2, 3, 4]
# JavaScript: values.map(v => v * 2)
# Python: map returns an iterator
doubled_iterator = map(lambda v: v * 2, values)
# Convert to list only when necessary
doubled_list = list(doubled_iterator)
# Equivalent comprehension (often preferred)
doubled_comp = [v * 2 for v in values]
Pitfall Guide
-
Mutable Default Arguments
- Explanation: Using a mutable object (like a list or dict) as a default argument creates a shared instance across all calls.
- Fix: Use
None as the default and initialize inside the function.
- Bad:
def append_item(item, lst=[]): lst.append(item)
- Good:
def append_item(item, lst=None): lst = lst or []; lst.append(item)
-
Confusing == and is
- Explanation:
== checks value equality; is checks object identity (memory address). JavaScript developers often misuse is expecting strict equality.
- Fix: Use
is only for singletons like None, True, or False.
- Pattern:
if result is None:
-
Ignoring Lazy Evaluation
- Explanation: Calling
map() or filter() does not execute immediately. Attempting to access indices or length on the result will fail.
- Fix: Wrap in
list() or iterate directly.
- Impact: Prevents
TypeError when treating iterators as sequences.
-
Overusing global
- Explanation: Modifying global state leads to race conditions and makes testing difficult.
- Fix: Pass variables as arguments or encapsulate state in classes.
- Best Practice: Minimize global scope usage to constants only.
-
Dot Notation on Dictionaries
- Explanation: JavaScript developers often try
dict.key, which raises an AttributeError.
- Fix: Always use
dict["key"] or dict.get("key").
- Note: This prevents collisions with dictionary methods like
.keys() or .items().
-
Indexing vs. Slicing Bounds
- Explanation: Accessing an index out of bounds raises
IndexError. Slicing out of bounds returns an empty list safely.
- Fix: Use slicing for safe extraction; use indexing when exact presence is required.
- Pattern:
safe_slice = data[10:20] vs risky_index = data[10].
-
Indentation Inconsistency
- Explanation: Mixing tabs and spaces causes
IndentationError. Python relies on whitespace for block structure.
- Fix: Configure editor to use 4 spaces per indent. Use a linter like
flake8 or formatter like black.
Production Bundle
Action Checklist
Decision Matrix
| Scenario | Recommended Approach | Why | Cost Impact |
|---|
| Fixed Data Structure | Tuple | Immutable, hashable, lower memory overhead. | Low |
| Dynamic Collection | List | Mutable, supports slicing and appends. | Low |
| Key-Value Lookup | Dictionary | O(1) average time complexity for access. | Low |
| Complex Filtering | List Comprehension | Faster execution and clearer intent than loops. | Low |
| Large Dataset Transform | Generator Expression | Lazy evaluation prevents memory spikes. | Low |
| Configuration | Dictionary with .get() | Safe access with defaults avoids crashes. | Low |
Configuration Template
Use this pyproject.toml configuration to set up a modern Python development environment with linting and formatting.
[tool.black]
line-length = 88
target-version = ['py39']
[tool.flake8]
max-line-length = 88
extend-ignore = ["E203", "W503"]
[tool.mypy]
strict = true
warn_return_any = true
warn_unused_configs = true
Quick Start Guide
- Initialize Environment: Run
python -m venv .venv to create an isolated virtual environment.
- Activate Shell: Execute
source .venv/bin/activate (Linux/macOS) or .venv\Scripts\activate (Windows).
- Install Tooling: Run
pip install black flake8 mypy to add formatting and type checking.
- Create Script: Write
main.py using the patterns above. Ensure indentation uses 4 spaces.
- Execute: Run
python main.py and verify output. Apply black . to auto-format code.