Iterating Over Lists, Strings, and Ranges
π·οΈ Loops and Iteration / The For Loop
π± Context Introduction
When you start working with Python, you'll quickly realize that you often need to repeat an action for every item in a collection. Whether you're processing server names from a list, checking characters in a log string, or generating a sequence of numbers for a batch job, the for loop is your go-to tool. It lets you walk through each element one by one without writing repetitive code.
βοΈ What Does "Iterating" Mean?
Iterating simply means going through each item in a sequence, one at a time. Python's for loop handles this automatically. You don't need to manage an index or a counterβPython does the heavy lifting for you.
- A for loop takes each element from a collection and assigns it to a variable.
- The code inside the loop runs once for every element.
- When there are no more elements, the loop stops.
π Iterating Over Lists
Lists are one of the most common data structures you'll work with. You might have a list of IP addresses, hostnames, or error codes.
Basic Example:
- You have a list: server_list = ["web01", "db01", "cache01"]
- You want to print each server name.
- Your loop looks like: for server in server_list: print(server)
- Python will output: web01, then db01, then cache01 on separate lines.
What's happening here?
- The variable server takes the value of the first item in the list.
- The print() statement runs.
- Then server takes the value of the second item, and so on.
Practical use for engineers:
- Looping through a list of log file paths to check their sizes.
- Iterating over a list of configuration files to apply changes.
- Processing a list of user IDs from a CSV export.
π Iterating Over Strings
Strings in Python are sequences of characters. You can loop through a string just like you loop through a list.
Basic Example:
- You have a string: log_entry = "ERROR"
- You want to print each character.
- Your loop looks like: for char in log_entry: print(char)
- Python will output: E, then R, then R, then O, then R on separate lines.
Why is this useful?
- Parsing log messages character by character.
- Validating input strings (checking for specific characters).
- Building new strings based on conditions (e.g., masking sensitive data).
Key difference from lists:
- Lists contain items (numbers, strings, objects).
- Strings contain individual characters.
- Both can be iterated the same way.
π Iterating Over Ranges
Sometimes you don't have a list or a stringβyou just need to repeat an action a specific number of times. That's where range() comes in.
Basic Example:
- You want to run a task 5 times.
- Your loop looks like: for i in range(5): print("Checking system...")
- Python will print "Checking system..." five times.
What is range()?
- range(5) generates numbers from 0 to 4 (5 numbers total).
- range(1, 6) generates numbers from 1 to 5.
- range(1, 10, 2) generates numbers from 1 to 9 stepping by 2 (1, 3, 5, 7, 9).
Practical use for engineers:
- Running a health check 3 times with a delay between each.
- Generating port numbers from 8000 to 8010 for testing.
- Creating numbered backup files (backup_1, backup_2, etc.).
π οΈ Comparison Table: Lists vs Strings vs Ranges
| Feature | Lists | Strings | Ranges |
|---|---|---|---|
| What you iterate over | Items (any data type) | Characters (single letters, spaces, symbols) | Numbers (integers) |
| Typical use case | Processing collections of data | Parsing or analyzing text | Repeating actions a set number of times |
| Can you modify it? | Yes, lists are mutable | No, strings are immutable | No, range is immutable |
| Example | ["srv1", "srv2", "srv3"] | "status_ok" | range(10) |
| Loop variable holds | The actual item from the list | A single character | A number (0, 1, 2, ...) |
π΅οΈ Common Patterns and Tips
Using the loop variable meaningfully:
- When iterating over a list, name your variable something descriptive: for server in server_list is better than for x in server_list.
- When using range(), the variable i is a common convention, but you can name it anything: for attempt in range(3).
Combining with other tools:
- You can use len() with range() to iterate by index: for i in range(len(server_list)): print(server_list[i]).
- But the direct method for server in server_list is cleaner and preferred.
Nested loops:
- You can put a loop inside another loop. For example, iterating over a list of servers and for each server, iterating over a list of services to check.
Breaking out early:
- Use break to stop the loop early if a condition is met.
- Use continue to skip the current item and move to the next one.
β Summary
- Lists let you iterate over collections of data like server names or IP addresses.
- Strings let you iterate over individual characters for parsing or validation.
- Ranges let you repeat actions a specific number of times or generate sequences of numbers.
- The for loop syntax is consistent across all three: for variable in sequence:
- Choose the right tool based on what you need to process: items, characters, or numbers.
Mastering these three iteration patterns will cover most of your daily looping needs as you work with Python in your engineering tasks.
The for loop lets you step through each item in a list, each character in a string, or each number in a range, one at a time.
π§ Example 1: Iterating over a list of numbers
This example shows how to print each number in a list, one per line.
numbers = [10, 20, 30, 40, 50]
for number in numbers:
print(number)
π€ Output: 10 20 30 40 50 (each on its own line)
π€ Example 2: Iterating over a string character by character
This example shows how to print each letter in a word, one per line.
word = "hello"
for letter in word:
print(letter)
π€ Output: h e l l o (each on its own line)
π’ Example 3: Iterating over a range of numbers
This example shows how to print numbers from 0 up to (but not including) 5.
for number in range(5):
print(number)
π€ Output: 0 1 2 3 4 (each on its own line)
π Example 4: Using range with start and stop values
This example shows how to print numbers starting at 2 and stopping before 7.
for number in range(2, 7):
print(number)
π€ Output: 2 3 4 5 6 (each on its own line)
π οΈ Example 5: Practical use β summing values in a list
This example shows how to add up all numbers in a list using a for loop.
prices = [15, 25, 10, 30, 20]
total = 0
for price in prices:
total = total + price
print(total)
π€ Output: 100
π Comparison Table
| Iteration Target | What You Get Each Loop | Example Output |
|---|---|---|
List [10, 20, 30] |
Each item: 10, then 20, then 30 | 10 20 30 |
String "abc" |
Each character: 'a', then 'b', then 'c' | a b c |
Range range(4) |
Numbers: 0, 1, 2, 3 | 0 1 2 3 |
Range range(2, 5) |
Numbers: 2, 3, 4 | 2 3 4 |
π± Context Introduction
When you start working with Python, you'll quickly realize that you often need to repeat an action for every item in a collection. Whether you're processing server names from a list, checking characters in a log string, or generating a sequence of numbers for a batch job, the for loop is your go-to tool. It lets you walk through each element one by one without writing repetitive code.
βοΈ What Does "Iterating" Mean?
Iterating simply means going through each item in a sequence, one at a time. Python's for loop handles this automatically. You don't need to manage an index or a counterβPython does the heavy lifting for you.
- A for loop takes each element from a collection and assigns it to a variable.
- The code inside the loop runs once for every element.
- When there are no more elements, the loop stops.
π Iterating Over Lists
Lists are one of the most common data structures you'll work with. You might have a list of IP addresses, hostnames, or error codes.
Basic Example:
- You have a list: server_list = ["web01", "db01", "cache01"]
- You want to print each server name.
- Your loop looks like: for server in server_list: print(server)
- Python will output: web01, then db01, then cache01 on separate lines.
What's happening here?
- The variable server takes the value of the first item in the list.
- The print() statement runs.
- Then server takes the value of the second item, and so on.
Practical use for engineers:
- Looping through a list of log file paths to check their sizes.
- Iterating over a list of configuration files to apply changes.
- Processing a list of user IDs from a CSV export.
π Iterating Over Strings
Strings in Python are sequences of characters. You can loop through a string just like you loop through a list.
Basic Example:
- You have a string: log_entry = "ERROR"
- You want to print each character.
- Your loop looks like: for char in log_entry: print(char)
- Python will output: E, then R, then R, then O, then R on separate lines.
Why is this useful?
- Parsing log messages character by character.
- Validating input strings (checking for specific characters).
- Building new strings based on conditions (e.g., masking sensitive data).
Key difference from lists:
- Lists contain items (numbers, strings, objects).
- Strings contain individual characters.
- Both can be iterated the same way.
π Iterating Over Ranges
Sometimes you don't have a list or a stringβyou just need to repeat an action a specific number of times. That's where range() comes in.
Basic Example:
- You want to run a task 5 times.
- Your loop looks like: for i in range(5): print("Checking system...")
- Python will print "Checking system..." five times.
What is range()?
- range(5) generates numbers from 0 to 4 (5 numbers total).
- range(1, 6) generates numbers from 1 to 5.
- range(1, 10, 2) generates numbers from 1 to 9 stepping by 2 (1, 3, 5, 7, 9).
Practical use for engineers:
- Running a health check 3 times with a delay between each.
- Generating port numbers from 8000 to 8010 for testing.
- Creating numbered backup files (backup_1, backup_2, etc.).
π οΈ Comparison Table: Lists vs Strings vs Ranges
| Feature | Lists | Strings | Ranges |
|---|---|---|---|
| What you iterate over | Items (any data type) | Characters (single letters, spaces, symbols) | Numbers (integers) |
| Typical use case | Processing collections of data | Parsing or analyzing text | Repeating actions a set number of times |
| Can you modify it? | Yes, lists are mutable | No, strings are immutable | No, range is immutable |
| Example | ["srv1", "srv2", "srv3"] | "status_ok" | range(10) |
| Loop variable holds | The actual item from the list | A single character | A number (0, 1, 2, ...) |
π΅οΈ Common Patterns and Tips
Using the loop variable meaningfully:
- When iterating over a list, name your variable something descriptive: for server in server_list is better than for x in server_list.
- When using range(), the variable i is a common convention, but you can name it anything: for attempt in range(3).
Combining with other tools:
- You can use len() with range() to iterate by index: for i in range(len(server_list)): print(server_list[i]).
- But the direct method for server in server_list is cleaner and preferred.
Nested loops:
- You can put a loop inside another loop. For example, iterating over a list of servers and for each server, iterating over a list of services to check.
Breaking out early:
- Use break to stop the loop early if a condition is met.
- Use continue to skip the current item and move to the next one.
β Summary
- Lists let you iterate over collections of data like server names or IP addresses.
- Strings let you iterate over individual characters for parsing or validation.
- Ranges let you repeat actions a specific number of times or generate sequences of numbers.
- The for loop syntax is consistent across all three: for variable in sequence:
- Choose the right tool based on what you need to process: items, characters, or numbers.
Mastering these three iteration patterns will cover most of your daily looping needs as you work with Python in your engineering tasks.
Interactive Views
You are currently in π All-in-One mode. Use the tabs at the top to switch to π Theory Only or π» Code Only views.
The for loop lets you step through each item in a list, each character in a string, or each number in a range, one at a time.
π§ Example 1: Iterating over a list of numbers
This example shows how to print each number in a list, one per line.
numbers = [10, 20, 30, 40, 50]
for number in numbers:
print(number)
π€ Output: 10 20 30 40 50 (each on its own line)
π€ Example 2: Iterating over a string character by character
This example shows how to print each letter in a word, one per line.
word = "hello"
for letter in word:
print(letter)
π€ Output: h e l l o (each on its own line)
π’ Example 3: Iterating over a range of numbers
This example shows how to print numbers from 0 up to (but not including) 5.
for number in range(5):
print(number)
π€ Output: 0 1 2 3 4 (each on its own line)
π Example 4: Using range with start and stop values
This example shows how to print numbers starting at 2 and stopping before 7.
for number in range(2, 7):
print(number)
π€ Output: 2 3 4 5 6 (each on its own line)
π οΈ Example 5: Practical use β summing values in a list
This example shows how to add up all numbers in a list using a for loop.
prices = [15, 25, 10, 30, 20]
total = 0
for price in prices:
total = total + price
print(total)
π€ Output: 100
π Comparison Table
| Iteration Target | What You Get Each Loop | Example Output |
|---|---|---|
List [10, 20, 30] |
Each item: 10, then 20, then 30 | 10 20 30 |
String "abc" |
Each character: 'a', then 'b', then 'c' | a b c |
Range range(4) |
Numbers: 0, 1, 2, 3 | 0 1 2 3 |
Range range(2, 5) |
Numbers: 2, 3, 4 | 2 3 4 |