0
0
DSA Pythonprogramming~15 mins

Traversal Forward and Backward in DSA Python - Build from Scratch

Choose your learning style9 modes available
Traversal Forward and Backward
📖 Scenario: Imagine you have a list of daily temperatures recorded in order. You want to look at these temperatures both from the start to the end (forward) and from the end back to the start (backward) to understand the pattern.
🎯 Goal: You will create a list of temperatures, then write code to traverse this list forward and backward, printing the temperatures in both directions.
📋 What You'll Learn
Create a list called temperatures with exact values: [23, 25, 21, 19, 22]
Create a variable called length that stores the length of the temperatures list
Use a for loop with variable i to traverse temperatures forward from index 0 to length - 1
Use a for loop with variable i to traverse temperatures backward from index length - 1 to 0
Print the temperatures in forward order separated by spaces
Print the temperatures in backward order separated by spaces
💡 Why This Matters
🌍 Real World
Traversing data forward and backward is useful in many real-life situations like reading sensor data, browsing history, or undo-redo operations.
💼 Career
Understanding how to move through data structures in both directions is a fundamental skill for software developers, data analysts, and anyone working with ordered data.
Progress0 / 4 steps
1
Create the temperature list
Create a list called temperatures with these exact values: [23, 25, 21, 19, 22]
DSA Python
Hint

Use square brackets to create a list and separate numbers with commas.

2
Create a variable for the list length
Create a variable called length that stores the length of the temperatures list using the len() function
DSA Python
Hint

Use len(temperatures) to get the number of items in the list.

3
Traverse the list forward and backward
Use a for loop with variable i to traverse temperatures forward from index 0 to length - 1 and print each temperature separated by spaces. Then use another for loop with variable i to traverse temperatures backward from index length - 1 to 0 and print each temperature separated by spaces.
DSA Python
Hint

Use range(length) for forward and range(length - 1, -1, -1) for backward traversal.

4
Print the forward and backward traversal results
Print the temperatures in forward order separated by spaces, then print the temperatures in backward order separated by spaces. The output should be exactly:
23 25 21 19 22
22 19 21 25 23
DSA Python
Hint

Check your print statements and loops to ensure the output matches exactly.