Iteration

What is iteration?

  • In programming, iteration refers to the process of repeating a set of instructions until a specific condition is met. This can be achieved using loop structures like for loops and while loops.

For Loops

A for loop is used to iterate over a sequence (e.g. a list, tuple, string, etc.) and execute a set of statements for each item in the sequence. Here's the basic syntax of a for loop in Python:

sequence = [1,2,3,4,5,6,7]
for variable in sequence:
    print(variable)
1
2
3
4
5
6
7
my_string = "Hello, World!"

for character in my_string:
    print(character)
H
e
l
l
o
,
 
W
o
r
l
d
!

While Loops A while loop is used to repeat a set of statements as long as a condition is true. Here's the basic syntax of a while loop in Python:

num = 0

while num < 5:
    print(num)
    num += 1
0
1
2
3
4

Applications of Iteration

Iteration is a fundamental concept in computer programming and is used in a variety of real-life applications. Here are some examples:

Data Processing

  • Data processing often involves iterating over large datasets to perform specific operations on each element. For example, in a data analysis task, you might iterate over a list of numbers to compute the average, or iterate over a list of strings to find the longest string.

User Interfaces

  • User interfaces often involve iteration to display and handle data from various sources. For example, in a web application, you might iterate over a list of users to display their information in a table. Similarly, in a desktop application, you might iterate over a list of files to display them in a file explorer.

Machine Learning

  • Machine learning algorithms often involve iterative processes to train models and improve their accuracy. For example, in a gradient descent algorithm, you might iterate over a set of training data to update the model's parameters and minimize the loss function.

Popcorn hack

  1. make a list related to your CPT project
  2. make a while loop that will print each term in the list
  3. make a for loop that will print each term in the list

simulation mechanics

In Python, pop() is a method that is used to remove and return an element from a list. The syntax for using pop() is as follows:

my_list = [1, 2, 3, 4, 5]
print(my_list)
my_list.pop()
print(my_list)
my_list.pop(1)
print(my_list)
[1, 2, 3, 4, 5]
[1, 2, 3, 4]
[1, 3, 4]

In Python, append() is a built-in method that is used to add an element to the end of a list. The syntax for using append() is as follows:

my_list = []
my_list.append(1)
my_list.append(2)
my_list.append(3)
print(my_list)
[1, 2, 3]