Iterate list

2 snippets across 2 stacks — Bash & Linux, Python

SHBash & Linux

For Loop

SH · Bash Scripting
syntax
for var in list; do
  commands
done
example
for host in web01 web02 web03; do
  echo "Deploying to ${host}..."
  scp app.tar.gz deploy@"${host}":/opt/releases/
done

# C-style:
for ((i=1; i<=5; i++)); do
  echo "Attempt ${i}"
done
output
Deploying to web01...
Deploying to web02...
Deploying to web03...

Note Never parse ls output in a for loop. Use globs instead: for f in *.log; do ... done. For iterating over lines in a file: while IFS= read -r line; do ... done < file.txt.

PYPython

for Loops

PY · Control Flow
syntax
for item in iterable:
    ...
example
total = 0
prices = [12.50, 8.99, 24.00]
for price in prices:
    total += price
print(f"Total: ${total:.2f}")

for i in range(3):
    print(f"Attempt {i + 1}")
output
Total: $45.49
Attempt 1
Attempt 2
Attempt 3

Note range(n) produces 0 through n-1. Use range(start, stop, step) for more control. Python for loops iterate over any iterable, not just numeric ranges.