Delete Set public Set private Add tags Delete tags
  Add tag   Cancel
  Delete tag   Cancel
  • • DevOps notes •
  •  
  • AI
  • Tags
  • Login

Range, zip/shaare/YcrfAg

  • python
  • python

Efficient Looping: range

  • Creating large lists for loops is memory-intensive (e.g., list(range(1_000_000))).
  • range() stores only start, stop, and step values, not all numbers.
  • Numbers are generated one at a time during iteration, reducing memory usage.
  • Ideal for loops needing a fixed number of iterations without large allocations.
import sys

number_count = 10_000_000

numbers_list = list(range(number_count))
numbers_range = range(number_count)

list_mb = sys.getsizeof(numbers_list) / (1024**2)
range_mb = sys.getsizeof(numbers_range) / (1024**2)

print(f"List size: {list_mb:.2f}")
print(f"Range size: {range_mb:.6f}")
print(f"List uses {(list_mb / range_mb):.2f} more memory!")

Using range()

  • range(stop): iterate from 0 up to (but not including) stop.
  • range(start, stop): iterate from start up to stop.
  • range(start, stop, step): iterate with a custom step increment.
for i in range(5):
    print(f"Retry #{i}")

for year in range(2020, 2024):
    print(f"Processing logs for {year}")

for server_id in range(10, 30, 5):
    print(f"Checking server {server_id}")

Getting Index + Value: enumerate()

  • Use enumerate(iterable, start=0) to get (index, item) tuples.
  • The start parameter sets the initial index value.
servers = ["web01", "web02", "web03"]

for idx, server in enumerate(servers, 1):
    print(f"#{idx}: Processing server {server}")

Parallel Iteration: zip()

  • Use zip(*iterables) to pair items from multiple iterables.
  • Iteration stops when the shortest iterable is exhausted.
hosts = ["hostA", "hostB", "hostC"]
ips = ["10.0.0.1", "10.0.0.2"]
azs = ["us-east-1a", "us-east-1b"]

for host, ip, az in zip(hosts, ips, azs):
    print(f"Host: {host}, IP: {ip}, AZ: {az}")
2 months ago Permalink
cluster icon
  • Dictionaries : Dictionaries (dict) Dictionaries are mutable, insertion-ordered collections of key-value pairs. Keys must be unique and immutable; values can be of an...
  • Concise Iteration: List Comprehensions : Concise Iteration: List Comprehensions Simple for loops to create lists can be verbose. We can leverage list comprehensions to define the list content...
  • Handling Authentication : Handling Authentication APIs often require authentication to control access, rate limits, and auditing. Without authentication, requests to protected...
  • Generators : Generators Writing a class-based iterator requires __iter__() and __next__(), plus manual state management and StopIteration handling. Generator fu...
  • Functions, Docstrings : Functions Functions package reusable code into named blocks, improving modularity, readability, and testability. They prevent duplication (DRY) and ma...


(97)
Filter untagged links
Fold Fold all Expand Expand all Are you sure you want to delete this link? Are you sure you want to delete this tag? The personal, minimalist, super-fast, database free, bookmarking service by the Shaarli community