Looping in Python

Day 10: Python Syntax: Basic Concepts —Looping Through Different Data Types python example.

Introduction

Welcome to Day 10! Now that you understand the basic for loop from yesterday’s lesson, it’s time to see its true power. One of the most common and essential tasks in programming is iterating through the items in a data structure. Today, we’ll explore how to use a for loop to seamlessly work with Python’s core data types, giving you a deep understanding of looping in Python.

The for loop’s strength lies in its ability to handle any iterable object, which includes all the primary data structures we’ve discussed. Let’s dive into how to apply looping in Python to each one.

 Looping in Python

Looping Through a List

Lists are ordered collections, making them a perfect fit for a for loop. The loop will process each item in the list, from the first to the last. This is the most common and readable way to iterate through a list.

Python
fruits = ["apple", "banana", "cherry"]

# Basic looping through a list
for fruit in fruits:
    print(fruit)

# Output:
# apple
# banana
# cherry

If you need the index of each item as well, you can use the built-in enumerate() function. It returns both the index and the item for each iteration, which is incredibly useful.

Python
for index, fruit in enumerate(fruits):
    print(f"Index {index}: {fruit}")

# Output:
# Index 0: apple
# Index 1: banana
# Index 2: cherry
Looping Through a List

Looping Through a Tuple

A tuple is very similar to a list in that it is an ordered collection. Therefore, looping in Python through a tuple works exactly the same way.

Python
coordinates = (10, 20, 30)

for point in coordinates:
    print(point)

# Output:
# 10
# 20
# 30

This is particularly useful when you have a list of tuples and need to unpack the values in the loop.

Python
students = [("Alice", 25), ("Bob", 22), ("Charlie", 28)]

for name, age in students:
    print(f"{name} is {age} years old.")

# Output:
# Alice is 25 years old.
# Bob is 22 years old.
# Charlie is 28 years old.
Looping Through a Tuple

Looping Through a Dictionary

Dictionaries store data in key-value pairs, which gives you more options for looping in Python. By default, a for loop will iterate through a dictionary’s keys.

Python
person = {"name": "tom", "age": 30, "city": "dallas"}

# Loop through keys (the default behavior)
for key in person:
    print(key)

# Output:
# name
# age
# city

To loop through the values or both the keys and values, you can use a dictionary’s built-in methods, such as dict.keys(), dict.values(), or the most common dict.items().

Python

# Loop through values using the .values() method
for value in person.values():
    print(value)

# Output:
# tom
# 30
# dallas

# Loop through both key-value pairs using the .items() method
for key, value in person.items():
    print(f"{key}: {value}")

# Output:
# name: tom
# age: 30
# city: dallas

Using the .items() method is often the most useful approach, as it gives you access to both parts of the dictionary entry at the same time. The Python documentation for dictionary methods is an excellent resource for learning more.

Looping Through a Dictionary

Looping Through a Set

A set is an unordered collection of unique items. When you loop through a set, the order of the items may not be the same as the order they were inserted, which is a key difference from lists and tuples.

Python
unique_numbers = {1, 2, 3, 4}

for number in unique_numbers:
    print(number)

# Output (order may vary):
# 1
# 2
# 3
# 4

For most practical purposes, the order of iteration in a set is not a concern, as sets are typically used when you only care about the presence of an item, not its position.

Looping Through a Set

Looping Through a String

Strings are also sequences of characters, so you can easily loop through each character in a string. This is a fundamental looping in Python example for processing text.

Python

text = “Hello” for char in text: print(char) # Output: # H # e # l # l # o

Looping Through a String

Combining Loops with Other Concepts

One of the most powerful aspects of looping in Python is combining for loops with other control flow statements.

  • Conditional Statements (if): You can use if statements inside a loop to perform an action only when a certain condition is met.
  • Loop Control Statements (break, continue): The break statement immediately exits the loop, while the continue statement skips the current iteration and moves to the next one. For more, see the Python tutorial on control flow.
Python
numbers = [1, 5, 10, 15, 20]
for num in numbers:
    if num > 10:
        break  # Exit the loop if the number is greater than 10
    print(num)

# Output:
# 1
# 5
# 10

for num in numbers:
    if num % 2 != 0:
        continue # Skip odd numbers
    print(num)

# Output:
# 10
# 20

Summary

Today, you learned how flexible and powerful looping in Python is by using the for loop to iterate over Python’s main data types.

  • Lists and Tuples: Loop directly through them to access each item. Use enumerate() if you need the index.
  • Dictionaries: Use the .keys(), .values(), or .items() methods to access what you need.
  • Sets and Strings: Loop directly through them to access each element, keeping in mind that sets are unordered.
  • Control Flow: Combine loops with if, break, and continue to build more sophisticated logic.

This foundational knowledge is a critical step in your programming journey, as it allows you to process and manipulate any collection of data.


The journey of learning what Python is is an exciting one, and this “30 Days of Python” series is designed to be your roadmap. Happy coding!

image 35 Simply Creative Minds

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *