Syntax Expressions and For Loops

🏷️ Lists and List Operations / List Comprehensions

Welcome to the world of Python syntax expressions and for loops! As you begin your journey with Python, understanding how to write clean, efficient loops and expressions is essential. This guide will help you grasp the fundamentals of for loops and syntax expressionsβ€”two building blocks that will appear in almost every script you write.


🧠 What Are Syntax Expressions and For Loops?

Syntax expressions are the rules and structures that define how you write code in Python. They include everything from variable assignments to conditional statements. For loops are a type of syntax expression that allow you to repeat a block of code for each item in a sequence (like a list, string, or range).

Think of a for loop as a conveyor belt: each item on the belt gets processed one at a time until the belt is empty.


βš™οΈ The Basic For Loop Structure

A for loop in Python follows a simple pattern:

  • Keyword: Start with the word for
  • Variable: Choose a name for the current item (e.g., item, x, name)
  • Keyword: Use the word in
  • Sequence: Provide the list, string, or range to iterate over
  • Colon: End the line with a colon :
  • Indented block: Write the code to execute for each item, indented by 4 spaces

Example: - for fruit in ["apple", "banana", "cherry"]: then on the next line, print(fruit) (indented by 4 spaces) - Expected output: apple, then banana, then cherry (each on a new line)


πŸ› οΈ Common For Loop Patterns

Here are the most useful patterns you will encounter:

Looping over a list: - servers = ["web01", "web02", "db01"] - for server in servers: then print(f"Checking {server}") - This prints a message for each server in the list

Looping over a range of numbers: - for i in range(5): then print(i) - This prints numbers 0, 1, 2, 3, 4 (range starts at 0 by default) - range(5) creates a sequence of 5 numbers: 0 through 4

Looping with start and end: - for i in range(1, 6): then print(i) - This prints numbers 1, 2, 3, 4, 5 (starts at 1, stops before 6)

Looping with step: - for i in range(0, 10, 2): then print(i) - This prints even numbers: 0, 2, 4, 6, 8


πŸ“Š For Loops vs. While Loops

Both loops repeat code, but they are used in different situations:

Feature For Loop While Loop
When to use When you know how many times to loop When you loop until a condition changes
Sequence required Yes (list, range, string) No (just a condition)
Risk of infinite loop Low (sequence ends naturally) High (if condition never becomes False)
Common use case Iterating over items Waiting for a specific state
Example for item in list: while count < 10:

πŸ•΅οΈ Using For Loops with Strings

Strings are sequences of characters, so you can loop over them:

  • word = "hello"
  • for char in word: then print(char)
  • This prints each character: h, e, l, l, o (each on a new line)

This is useful when you need to examine or transform each character in a string.


🧩 The enumerate() Function

When you need both the index and the value from a list, use enumerate():

  • servers = ["web01", "web02", "db01"]
  • for index, server in enumerate(servers): then print(f"{index}: {server}")
  • Expected output: 0: web01, then 1: web02, then 2: db01

The index starts at 0 by default. You can change the starting number: - for index, server in enumerate(servers, start=1): then print(f"{index}: {server}") - Expected output: 1: web01, then 2: web02, then 3: db01


πŸ”„ The zip() Function for Parallel Loops

When you have two lists of the same length and want to loop through them together:

  • names = ["Alice", "Bob", "Charlie"]
  • scores = [85, 92, 78]
  • for name, score in zip(names, scores): then print(f"{name}: {score}")
  • Expected output: Alice: 85, then Bob: 92, then Charlie: 78

zip() pairs up items from each list by their position.


🎯 Breaking and Continuing Loops

Control the flow of your loops with two special statements:

Break exits the loop entirely: - for number in range(10): then if number == 5: break then print(number) - This prints 0, 1, 2, 3, 4 and then stops (never prints 5 or beyond)

Continue skips the current iteration and moves to the next: - for number in range(5): then if number == 2: continue then print(number) - This prints 0, 1, 3, 4 (skips 2 entirely)


πŸ“ Practical Examples for Engineers

Example 1: Checking server status - servers = ["web01", "web02", "db01", "cache01"] - for server in servers: then print(f"Pinging {server}...") then print(f"{server} is online") - This simulates checking each server in a list

Example 2: Processing log lines - log_lines = ["INFO: started", "ERROR: timeout", "INFO: completed"] - for line in log_lines: then if "ERROR" in line: print(f"Alert: {line}") - This filters log lines and only prints error messages

Example 3: Generating configuration numbers - for port in range(8000, 8005): then print(f"Configuring port {port}") - This prints: Configuring port 8000, 8001, 8002, 8003, 8004


βœ… Quick Tips for Writing Clean For Loops

  • Use meaningful variable names: for server in servers is better than for s in list
  • Keep the indented block short (3-5 lines maximum)
  • If your loop body is getting long, consider moving the logic into a function
  • Use break and continue sparinglyβ€”they can make code harder to follow
  • Remember that range() is exclusive of the end value (stops before the number you specify)

πŸš€ Next Steps

Practice writing for loops with different sequences: 1. Loop over a list of IP addresses and print each one 2. Use range() to print the numbers 10 down to 1 3. Combine enumerate() with a list of configuration files 4. Use zip() to pair server names with their IP addresses

For loops are one of the most powerful tools in Python. Master them, and you will be able to automate almost any repetitive task you encounter!


This topic shows how to write compact list-building expressions using for loops inside square brackets.

πŸ”§ Example 1: Basic list comprehension with a simple for loop

Creates a list of squares from 0 to 4 using a single-line expression.

squares = [x**2 for x in range(5)]
print(squares)

πŸ“€ Output: [0, 1, 4, 9, 16]


πŸ”§ Example 2: List comprehension with a conditional filter

Keeps only even numbers from a range, then squares them.

even_squares = [x**2 for x in range(10) if x % 2 == 0]
print(even_squares)

πŸ“€ Output: [0, 4, 16, 36, 64]


πŸ”§ Example 3: Transforming strings in a list

Converts a list of names to uppercase using a comprehension.

names = ["alice", "bob", "charlie"]
upper_names = [name.upper() for name in names]
print(upper_names)

πŸ“€ Output: ['ALICE', 'BOB', 'CHARLIE']


πŸ”§ Example 4: Nested loops in a comprehension

Creates all pairs (x, y) where x is from 0 to 2 and y is from 0 to 2.

pairs = [(x, y) for x in range(3) for y in range(3)]
print(pairs)

πŸ“€ Output: [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]


πŸ”§ Example 5: Practical use β€” filtering and transforming sensor readings

Takes a list of temperature readings in Celsius, converts those above freezing to Fahrenheit.

celsius_readings = [0, 15, -5, 30, -10, 22]
warm_fahrenheit = [(c * 9/5 + 32) for c in celsius_readings if c > 0]
print(warm_fahrenheit)

πŸ“€ Output: [59.0, 86.0, 71.6]


Comparison: For Loop vs. List Comprehension

Feature Traditional For Loop List Comprehension
Lines of code 4–6 lines 1 line
Readability for simple tasks Clear but verbose Compact and clear
Performance Slower for large lists Faster (optimized internally)
Best use case Complex logic or side effects Simple transformations or filters

Welcome to the world of Python syntax expressions and for loops! As you begin your journey with Python, understanding how to write clean, efficient loops and expressions is essential. This guide will help you grasp the fundamentals of for loops and syntax expressionsβ€”two building blocks that will appear in almost every script you write.


🧠 What Are Syntax Expressions and For Loops?

Syntax expressions are the rules and structures that define how you write code in Python. They include everything from variable assignments to conditional statements. For loops are a type of syntax expression that allow you to repeat a block of code for each item in a sequence (like a list, string, or range).

Think of a for loop as a conveyor belt: each item on the belt gets processed one at a time until the belt is empty.


βš™οΈ The Basic For Loop Structure

A for loop in Python follows a simple pattern:

  • Keyword: Start with the word for
  • Variable: Choose a name for the current item (e.g., item, x, name)
  • Keyword: Use the word in
  • Sequence: Provide the list, string, or range to iterate over
  • Colon: End the line with a colon :
  • Indented block: Write the code to execute for each item, indented by 4 spaces

Example: - for fruit in ["apple", "banana", "cherry"]: then on the next line, print(fruit) (indented by 4 spaces) - Expected output: apple, then banana, then cherry (each on a new line)


πŸ› οΈ Common For Loop Patterns

Here are the most useful patterns you will encounter:

Looping over a list: - servers = ["web01", "web02", "db01"] - for server in servers: then print(f"Checking {server}") - This prints a message for each server in the list

Looping over a range of numbers: - for i in range(5): then print(i) - This prints numbers 0, 1, 2, 3, 4 (range starts at 0 by default) - range(5) creates a sequence of 5 numbers: 0 through 4

Looping with start and end: - for i in range(1, 6): then print(i) - This prints numbers 1, 2, 3, 4, 5 (starts at 1, stops before 6)

Looping with step: - for i in range(0, 10, 2): then print(i) - This prints even numbers: 0, 2, 4, 6, 8


πŸ“Š For Loops vs. While Loops

Both loops repeat code, but they are used in different situations:

Feature For Loop While Loop
When to use When you know how many times to loop When you loop until a condition changes
Sequence required Yes (list, range, string) No (just a condition)
Risk of infinite loop Low (sequence ends naturally) High (if condition never becomes False)
Common use case Iterating over items Waiting for a specific state
Example for item in list: while count < 10:

πŸ•΅οΈ Using For Loops with Strings

Strings are sequences of characters, so you can loop over them:

  • word = "hello"
  • for char in word: then print(char)
  • This prints each character: h, e, l, l, o (each on a new line)

This is useful when you need to examine or transform each character in a string.


🧩 The enumerate() Function

When you need both the index and the value from a list, use enumerate():

  • servers = ["web01", "web02", "db01"]
  • for index, server in enumerate(servers): then print(f"{index}: {server}")
  • Expected output: 0: web01, then 1: web02, then 2: db01

The index starts at 0 by default. You can change the starting number: - for index, server in enumerate(servers, start=1): then print(f"{index}: {server}") - Expected output: 1: web01, then 2: web02, then 3: db01


πŸ”„ The zip() Function for Parallel Loops

When you have two lists of the same length and want to loop through them together:

  • names = ["Alice", "Bob", "Charlie"]
  • scores = [85, 92, 78]
  • for name, score in zip(names, scores): then print(f"{name}: {score}")
  • Expected output: Alice: 85, then Bob: 92, then Charlie: 78

zip() pairs up items from each list by their position.


🎯 Breaking and Continuing Loops

Control the flow of your loops with two special statements:

Break exits the loop entirely: - for number in range(10): then if number == 5: break then print(number) - This prints 0, 1, 2, 3, 4 and then stops (never prints 5 or beyond)

Continue skips the current iteration and moves to the next: - for number in range(5): then if number == 2: continue then print(number) - This prints 0, 1, 3, 4 (skips 2 entirely)


πŸ“ Practical Examples for Engineers

Example 1: Checking server status - servers = ["web01", "web02", "db01", "cache01"] - for server in servers: then print(f"Pinging {server}...") then print(f"{server} is online") - This simulates checking each server in a list

Example 2: Processing log lines - log_lines = ["INFO: started", "ERROR: timeout", "INFO: completed"] - for line in log_lines: then if "ERROR" in line: print(f"Alert: {line}") - This filters log lines and only prints error messages

Example 3: Generating configuration numbers - for port in range(8000, 8005): then print(f"Configuring port {port}") - This prints: Configuring port 8000, 8001, 8002, 8003, 8004


βœ… Quick Tips for Writing Clean For Loops

  • Use meaningful variable names: for server in servers is better than for s in list
  • Keep the indented block short (3-5 lines maximum)
  • If your loop body is getting long, consider moving the logic into a function
  • Use break and continue sparinglyβ€”they can make code harder to follow
  • Remember that range() is exclusive of the end value (stops before the number you specify)

πŸš€ Next Steps

Practice writing for loops with different sequences: 1. Loop over a list of IP addresses and print each one 2. Use range() to print the numbers 10 down to 1 3. Combine enumerate() with a list of configuration files 4. Use zip() to pair server names with their IP addresses

For loops are one of the most powerful tools in Python. Master them, and you will be able to automate almost any repetitive task you encounter!

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.

This topic shows how to write compact list-building expressions using for loops inside square brackets.

πŸ”§ Example 1: Basic list comprehension with a simple for loop

Creates a list of squares from 0 to 4 using a single-line expression.

squares = [x**2 for x in range(5)]
print(squares)

πŸ“€ Output: [0, 1, 4, 9, 16]


πŸ”§ Example 2: List comprehension with a conditional filter

Keeps only even numbers from a range, then squares them.

even_squares = [x**2 for x in range(10) if x % 2 == 0]
print(even_squares)

πŸ“€ Output: [0, 4, 16, 36, 64]


πŸ”§ Example 3: Transforming strings in a list

Converts a list of names to uppercase using a comprehension.

names = ["alice", "bob", "charlie"]
upper_names = [name.upper() for name in names]
print(upper_names)

πŸ“€ Output: ['ALICE', 'BOB', 'CHARLIE']


πŸ”§ Example 4: Nested loops in a comprehension

Creates all pairs (x, y) where x is from 0 to 2 and y is from 0 to 2.

pairs = [(x, y) for x in range(3) for y in range(3)]
print(pairs)

πŸ“€ Output: [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]


πŸ”§ Example 5: Practical use β€” filtering and transforming sensor readings

Takes a list of temperature readings in Celsius, converts those above freezing to Fahrenheit.

celsius_readings = [0, 15, -5, 30, -10, 22]
warm_fahrenheit = [(c * 9/5 + 32) for c in celsius_readings if c > 0]
print(warm_fahrenheit)

πŸ“€ Output: [59.0, 86.0, 71.6]


Comparison: For Loop vs. List Comprehension

Feature Traditional For Loop List Comprehension
Lines of code 4–6 lines 1 line
Readability for simple tasks Clear but verbose Compact and clear
Performance Slower for large lists Faster (optimized internally)
Best use case Complex logic or side effects Simple transformations or filters