engineering

Python For Loop (with examples)

Python For Loop (with examples)

Learn how to master Python for loops and the range() function with various examples and best practices for iterating through sequences, implementing counters, and optimizing your Python code.

Yogini Bende

Yogini Bende

Sep 19, 2024 7 min read

In the world of Python programming, mastering loops is essential for writing efficient and powerful code. Among the various looping constructs available, the for loop stands out as a versatile and widely-used tool. When combined with the range() function, it becomes an even more potent instrument in a Python developer's toolkit.

This comprehensive guide will delve into the intricacies of Python's for loops, with a special focus on using them in conjunction with the range() function. You can also read more in-depth about Python Features before jumping on this topic.

We'll start by exploring the fundamental concepts of for loops in Python, understanding their syntax and how they differ from loops in other programming languages. Then, we'll dive deep into the range() function, uncovering its versatility and the various ways it can be used to control loop iterations. Finally, we'll examine a series of practical examples that demonstrate the power and flexibility of for loops with range(), covering scenarios from basic counting to more complex algorithmic implementations.

So, let's get started

1. For Loops in Python

Python's for loop is a powerful and flexible construct that allows you to iterate over sequences (such as lists, tuples, dictionaries, sets, or strings) or other iterable objects. Unlike for loops in many other programming languages, Python's version is more akin to a "for-each" loop, making it intuitive and easy to use.

Syntax of a Python for loop

The basic syntax of a for loop in Python is as follows:

for item in iterable:
    # Code block to be executed for each item

Key components of a for loop:

  • item: A variable that takes on the value of the next element in the iterable on each iteration.
  • iterable: A sequence (list, tuple, string) or an iterable object.
  • The code block: Indented lines of code that are executed for each iteration of the loop.

Characteristics of Python for loops

  1. Simplicity: Python's for loops are designed to be simple and readable, abstracting away the complexities of manual indexing.

  2. Versatility: They can iterate over various types of sequences and iterable objects, not just numerical ranges.

  3. Automatic termination: The loop automatically terminates when all items in the sequence have been processed.

  4. Iterable unpacking: Python allows unpacking of iterable items directly in the loop declaration.

Examples of basic for loops

Let's look at some basic examples to illustrate the versatility of Python's for loops:

# Iterating over a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(f"I like {fruit}")

# Iterating over a string
for char in "Python":
    print(char)

# Iterating over a dictionary
person = {"name": "Alice", "age": 30, "city": "New York"}
for key, value in person.items():
    print(f"{key}: {value}")

# Using enumerate() for index and value
for index, fruit in enumerate(fruits):
    print(f"Index {index}: {fruit}")

These examples demonstrate how for loops can be used with different types of iterables, showcasing their flexibility in Python programming.

2. Range Function in Python

The range() function is a built-in Python function that generates a sequence of numbers. It's commonly used in conjunction with for loops to control the number of iterations or to generate numeric sequences. Understanding range() is crucial for mastering for loops in Python.

Syntax of range()

The range() function can be called with one, two, or three arguments:

range(stop)
range(start, stop)
range(start, stop, step)
  • start: The first number in the sequence (default is 0 if not specified)
  • stop: The number to stop before (this number is not included in the sequence)
  • step: The increment between each number in the sequence (default is 1 if not specified)

Characteristics of range()

  1. Lazy evaluation: range() doesn't generate all numbers at once but yields them one at a time, making it memory-efficient.

  2. Immutability: The sequence generated by range() is immutable.

  3. Versatility: It can generate various sequences, including reverse sequences and sequences with custom steps.

  4. Type: In Python 3, range() returns a range object, not a list. Use list(range()) to convert it to a list if needed.

Examples of using range()

Let's explore various ways to use the range() function:

# Basic range with one argument
for i in range(5):
    print(i)  # Outputs: 0, 1, 2, 3, 4

# Range with start and stop
for i in range(2, 8):
    print(i)  # Outputs: 2, 3, 4, 5, 6, 7

# Range with start, stop, and step
for i in range(1, 10, 2):
    print(i)  # Outputs: 1, 3, 5, 7, 9

# Reverse range
for i in range(10, 0, -1):
    print(i)  # Outputs: 10, 9, 8, 7, 6, 5, 4, 3, 2, 1

# Using range() to create a list
numbers = list(range(1, 6))
print(numbers)  # Outputs: [1, 2, 3, 4, 5]

These examples illustrate the flexibility of the range() function in generating various sequences for use in for loops and other contexts.

3. For Loop Examples

Now that we've covered the basics of for loops and the range() function, let's explore some practical examples that demonstrate their combined power in Python programming.

Example 1: Simple Counter

print("Countdown:")
for i in range(5, 0, -1):
    print(i)
print("Blast off!")

This example uses a for loop with range() to create a simple countdown timer.

Example 2: Sum of Numbers

sum = 0
for num in range(1, 101):
    sum += num
print(f"The sum of numbers from 1 to 100 is: {sum}")

Here, we use a for loop to calculate the sum of numbers from 1 to 100.

Example 3: Printing Multiplication Table

number = 5
print(f"Multiplication table for {number}:")
for i in range(1, 11):
    print(f"{number} x {i} = {number * i}")

This example generates a multiplication table for a given number.

Example 4: Iterating Over a List with Index

fruits = ["apple", "banana", "cherry", "date"]
for index in range(len(fruits)):
    print(f"Index {index}: {fruits[index]}")

Here, we use range() with len() to iterate over a list with both index and value.

Example 5: Nested Loops for 2D Grid

for i in range(3):
    for j in range(3):
        print(f"({i}, {j})", end=" ")
    print()  # New line after each row

This example demonstrates nested for loops to create a 2D grid pattern.

Example 6: Skipping Elements

for i in range(0, 10, 2):
    if i == 4:
        continue  # Skip 4
    print(i, end=" ")

This example shows how to use continue to skip specific iterations in a loop.

Example 7: Early Loop Termination

for i in range(1, 100):
    if i * i > 500:
        print(f"The first number whose square is > 500 is {i}")
        break

Here, we use a for loop with break to find the first number whose square is greater than 500.

Example 8: List Comprehension with Range

squares = [x**2 for x in range(1, 11)]
print(f"Squares of numbers from 1 to 10: {squares}")

This example demonstrates how to use range() in a list comprehension to generate a list of squares.

Python developer jobs

Last but not the least, if you are looking for jobs as a Python developer, you are at a right place. Check out Peerlist Jobs to find many remote jobs and apply them with your Peerlist Profile.

Conclusion

Mastering Python's for loops and the range() function is crucial for writing efficient and elegant code. These constructs offer a powerful way to iterate over sequences, generate numeric ranges, and control program flow.

If you are looking to learn other Python concepts like Switch Statement, you can check our other articles on this topic.

By honing your skills with these fundamental constructs, you'll be better equipped to tackle more complex programming challenges and write cleaner, more efficient Python code.

Happy coding, and may your loops always terminate as expected!

Join Peerlist

or continue with email

By clicking "Join Peerlist“ you agree to our Code of Conduct, Terms of Service and Privacy Policy.