Using Loops with Lists
When you need to process the data within a list sequentially, combining a for loop with the list enables efficient handling of the data.
Using for Loop with a List
Through loops, you can sequentially access elements in a list to perform specific tasks or to find elements that meet certain conditions conveniently.
products = ["laptop", "smartphone", "tablet"]
for product in products:
# When product is "smartphone"
if product == "smartphone":
print("smartphone found!")
# When product is not "smartphone"
else:
print(product)
The above code sequentially accesses each element of the products list. Using an if statement, it prints smartphone found! when the element is smartphone, and prints the element in other cases.
Processing List Elements Repeatedly
You can also use a for loop to batch process all elements within a list.
For example, if you want to apply the exponentiation operation to all elements of a number list, you can write the code as follows.
# List element processing
numbers = [1, 2, 3, 4, 5]
squared_numbers = []
# Apply exponentiation to each element in the numbers list
for number in numbers:
# Apply exponentiation using ** operator and add to squared_numbers list
squared_numbers.append(number ** 2)
# Prints [1, 4, 9, 16, 25]
print(squared_numbers)
The above code performs exponentiation on each element of the numbers list and adds the result to the squared_numbers list.
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.