Iterating over a list
Iterating (遍历、迭代) over a list is a core programming concept where you access each element in a sequence individually to perform an operation, such as printing or transforming data
While loop method
while-loop-iterate-list.py
py
# Add 1 on each of the number in a list
original_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# add all of the element by 1
index_of_list = 0
while index_of_list < len(original_list):
original_list[index_of_list] += 1
index_of_list += 1
print(original_list)Results:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]For loop method
for-loop-iterate-list.py
py
# Add 1 on each of the number in a list
original_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# add all of the element by 1
for i in original_list:
original_list[i] += 1
print(original_list)Results:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]Comprehensive usage
- Find
oddandevennumber from the list and store them in a seperated variable name and print them at the end. - Find
oddnumber by using for loop method. - Find
evennumber by using while loop method.
comprehensive-list-iterate.py
py
num_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
odd_num_list = []
even_num_list = []
# odd - for loop
# control item
# i for the item in a list
for item in num_list:
if item % 2 != 0:
odd_num_list.append(item)
# even - while loop
# control index
index_of_list = 0
while index_of_list < len(num_list):
if num_list[index_of_list] % 2 == 0:
even_num_list.append(num_list[index_of_list])
index_of_list += 1
print(f"Odd Number: {odd_num_list}")
print(f"Even Number: {even_num_list}")Results:
Odd Number: [1, 3, 5, 7, 9]
Even Number: [2, 4, 6, 8, 10]Conclusion
