Applying For Loops to Process Data in Python
One of the most common use cases for for loops in Python is to iterate over a list and perform some operation on each element. Here's an example of doubling the values in a list:
numbers = [1, 2, 3, 4, 5]
doubled_numbers = []
for num in numbers:
doubled_numbers.append(num * 2)
print(doubled_numbers) ## Output: [2, 4, 6, 8, 10]
Filtering Data Using For Loops
For loops can also be used to filter data based on certain conditions. Here's an example of creating a new list with only the even numbers from a given list:
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = []
for num in numbers:
if num % 2 == 0:
even_numbers.append(num)
print(even_numbers) ## Output: [2, 4, 6, 8, 10]
Summing and Averaging Data
For loops can be used to calculate the sum or average of a set of values. Here's an example of calculating the sum and average of a list of numbers:
numbers = [10, 20, 30, 40, 50]
total = 0
for num in numbers:
total += num
average = total / len(numbers)
print(f"Sum: {total}") ## Output: Sum: 150
print(f"Average: {average}") ## Output: Average: 30.0
Counting Occurrences in Data
For loops can be used to count the occurrences of specific elements in a sequence. Here's an example of counting the occurrences of each letter in a string:
text = "LabEx is a leading provider of AI and machine learning solutions."
letter_counts = {}
for char in text:
if char.isalpha():
if char in letter_counts:
letter_counts[char] += 1
else:
letter_counts[char] = 1
print(letter_counts)
This will output a dictionary with the letter counts:
{'L': 1, 'a': 3, 'b': 1, 'E': 1, 'x': 1, 'i': 3, 's': 3, 'p': 2, 'r': 2, 'o': 2, 'v': 1, 'd': 1, 'e': 4, 'r': 2, 'f': 1, 'A': 1, 'I': 1, 'm': 2, 'c': 1, 'h': 1, 'n': 1, 'l': 1, 'u': 1, 't': 1, 'i': 1, 'o': 1, 'n': 1, 's': 1, '.': 1}
By understanding how to apply for loops to process data in Python, you'll be able to perform a wide range of data manipulation and analysis tasks. In the next section, we'll explore some best practices and optimization techniques for working with for loops.