Skip to main content
Practice

Using for loops with Lists

Loops allow us to perform repetitive tasks by iterating over elements of an iterable object like lists, tuples, or strings.

In this lesson, we will explore how to use a for loop with a list to sequentially process each element of the list.


Utilizing a for loop with a List

A for loop accesses each element in a list and allows you to perform various operations or tasks using these elements.

Using a for loop with a List
# Create a list of numbers
numbers = [1, 2, 3, 4, 5]

# Create an empty list to store the results
squared_numbers = []

# Use a 'for' loop to calculate the square of each number and add it to the result list
for number in numbers:
# Calculate square
squared = number ** 2
# Append the calculated value to the list
squared_numbers.append(squared)

# Original list [1, 2, 3, 4, 5]
print("Original Numbers:", numbers)

# Squared result [1, 4, 9, 16, 25]
print("Squared Numbers:", squared_numbers)

Want to learn more?

Join CodeFriends Plus membership or enroll in a course to start your journey.