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.

Frequently asked questions

How do you iterate list?
This task is covered in 2 stacks on this page: Bash & Linux, Python. The "For Loop" snippet in Bash & Linux uses `for var in list; do`.
Which command does the Bash & Linux example use?
The "For Loop" snippet uses `for var in list; do`, from the Bash Scripting section of the Bash & Linux cheat sheet.
Which stacks cover "iterate list" on this page?
Bash & Linux, Python. Together they hold 2 copy-ready snippets for this task.
Is there anything to watch out for?
Yes. For "For Loop": 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.