Lecture
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)
Previous lessonHow to Perform Iterations Based on Conditions in PythonNext lessonNested Lists and Nested Loops
Lessons in this chapter Β· For Loop: Structure and Usage
- 1. How to Perform Iterations Based on Conditions in Python
- 2. Using `for` loops with Lists
- 3. Nested Lists and Nested Loops
- 4. Multiple-choice quiz
- 5. Expanding Sequence Elements with the Spread Operator
- 6. Utilizing for Loops with Dictionaries
- 7. How to Create a Range of Numbers in Python
- 8. Coding Quiz - for Loop
- 9. Multiple-choice quiz
- 10. Fill-in-the-blank quiz
Quiz
0 / 1
In a for loop, the colon (:) after the sequence is optional.
True
False
Lecture
AI Tutor
Design
Upload
Notes
Favorites
Help