Iterating over data structures



Iterating over data structures is a common task in programming. It allows you to perform an action on each element within a data structure, such as a list or a dictionary. In Python, you can use loops to accomplish this task. There are two types of loops in Python: for loops and while loops.

For Loops

A for loop iterates over a sequence of elements, such as a list or a string. Here is an example of a for loop that iterates over a list:

fruits = ['apple', 'banana', 'mango'] for fruit in fruits: print(fruit)

Output:

apple banana mango

In this example, the for loop iterates over each element in the list fruits and prints it to the console. The loop variable, fruit, takes on the value of each element in the list, one at a time.

You can also use the range() function to create a sequence of numbers to iterate over. For example:

for i in range(5): print(i)

Output:

0 1 2 3 4

The range() function creates a sequence of numbers from 0 to the number specified as an argument, in this case 5. The for loop then iterates over this sequence and prints each number to the console.

While Loops

A while loop repeats a block of code as long as a certain condition is true. For example:

i = 0 while i < 5: print(i) i += 1

Output:

0 1 2 3 4

In this example, the while loop will continue to execute as long as the value of i is less than 5. The value of i is incremented by 1 at the end of each loop iteration, so eventually the condition i < 5 will be false and the loop will terminate.

It's important to make sure that the condition of a while loop will eventually become false, or else the loop will continue to run indefinitely, known as an infinite loop.

Loop Control Statements

You can use loop control statements to change the behavior of a loop.

Break

The break statement terminates a loop prematurely, before the loop condition is false. For example:

fruits = ['apple', 'banana', 'mango', 'orange'] for fruit in fruits: if fruit == 'mango': break print(fruit)

Output:

apple banana

In this example, the loop terminates when it encounters the mango element in the list, and does not print the orange element.

Continue

The continue statement skips the rest of the current iteration and moves on to the next one. For example:

fruits = ['apple', 'banana', 'mango', 'orange'] for fruit in fruits: if fruit == 'banana': continue print(fruit)

Output:

apple mango orange

In this example, the banana element is skipped and not printed to the console.

Comments