Loop through each items

chevron-rightWhen to use loop for each item in listhashtag

Great follow-up, Pavan! πŸ‘ Let’s break down when to use a loop to go through each item in a list, especially from a DevOps and automation point of view.


βœ… When to use a loop for each item in a list

You use a for loop when you want to do the same action on multiple items, one by one.


πŸ”§ Real-world DevOps Use Cases:

Use Case
Why loop?

πŸ” Restart services on multiple servers

You have a list of server IPs and want to send a command to each

🐳 Stop multiple Docker containers

You have a list of container names to act on

☸️ Apply Kubernetes manifests in multiple namespaces

You want to repeat the kubectl apply command for each namespace

πŸ“‚ Back up several databases

Each database name in the list needs a pg_dump

πŸ” Health check multiple URLs

Each URL should be pinged or checked

πŸš€ Deploy multiple modules in Terraform

You need to cd into each module directory and run terraform apply


πŸ”„ Basic Format:

items = ["item1", "item2", "item3"]
for item in items:
    # do something with item
    print(item)

βœ… When to Use a Loop:

Situation
Use a Loop?

Same action needs to run for multiple items

βœ… Yes

You’re working with a list/array

βœ… Yes

You’re automating repetitive tasks

βœ… Yes

You want to avoid repeating code manually

βœ… Yes


❌ When not to use a loop:

Situation
Why not use a loop?

You only need to process one item

A loop adds unnecessary complexity

You need parallel or asynchronous processing

Use threading or async instead

You want to break early after a match

Maybe use a loop with break or an if instead


πŸ” Example from DevOps:

# Restart nginx on multiple servers
servers = ["10.0.0.1", "10.0.0.2", "10.0.0.3"]

for ip in servers:
    subprocess.run(f"ssh ubuntu@{ip} 'sudo systemctl restart nginx'", shell=True)

βœ… Summary:

Question
Answer

When should I use a loop over a list?

When you're performing repetitive actions on each element

What kind of data works well?

Lists, arrays, sets β€” anything iterable

Should I use enumerate() too?

Only if you need the index/position of the item


Let me know if you want to convert one of your tasks (like restart, deploy, backup) into a real Python loop example!

loop through each item of the list using enumerate

# Define a list of names
names = ["Alice", "Bob", "Charlie"]

# Use enumerate to loop through the list with both index (i) and value (name)
# The second argument '1' makes the index start from 1 instead of 0
for i, name in enumerate(names, 1):
    # Print the index and the name in a formatted string
    print(f"{i}. Name is {name}")

# List of server IP addresses
servers = ["10.0.0.1", "10.0.0.2", "10.0.0.3"]

# Loop with enumerate to get both index and IP
for i, ip in enumerate(servers):
    if i == 1:  # Only target the second server (index starts from 0)
        subprocess.run(f"ssh ubuntu@{ip} 'sudo systemctl restart nginx'", shell=True)

without enumerate

chevron-rightWhen to use enumerate or nothashtag

Great question, Pavan! πŸ™Œ Understanding when to use enumerate() and when not is a simple but powerful skill β€” especially in scripting and automation like DevOps.


βœ… Use enumerate() when:

🎯 Situation
πŸ” Reason

You need the index/position of the item

e.g., to skip the first item, or process only the 2nd

You want to number items in output

e.g., 1. Server is up, 2. Server is down

You need to reference list position + value together

e.g., Server-1: 10.0.0.1

You're generating unique names based on position

e.g., nginx_log_1.txt, nginx_log_2.txt

You're making conditional logic based on position

e.g., restart only the 3rd container


πŸ”§ Example:


❌ Don't use enumerate() when:

🚫 Situation
πŸ” Reason

You only need the values, not their positions

Index adds unnecessary complexity

You're not using the index at all in your loop body

Cleaner code = better code

You're using dictionaries (use .items() instead)

enumerate() is for sequences like lists/tuples


πŸ”§ Example without enumerate():

Here, the index doesn't matter β€” just loop and act.


πŸ” Quick Decision Chart:

Do you need index (position)?

Use enumerate()?

❌ No

❌ No

βœ… Yes

βœ… Yes


πŸ’‘ Pro Tip for DevOps:

In deployment, logging, and automation, if your logic or file naming depends on position, enumerate() is your best friend.

Let me know if you want a cheatsheet image or a downloadable version of this!

chevron-rightlooping command and collecting logshashtag

Last updated