For Loop Examples¶
Sum of First 100 Integers¶
# using range
# Sum the first 100 positive integers
total = 0
for i in range(1,101):
total += i**2
print(total)
338350
Sum of Square of First 100 Integers¶
# Using range
Sum of Squares of Elements in a List¶
# Using range(len(...))
# Using elements
Pairwise Sum¶
# Using range
Something involving Strings¶
Using Loops to Work with Lists¶
One common use of a loop is to perform an action on every element of a list. In this case, we typically use the loop counter as an index for elements in the list.
The list below contains 30 integer values, several of which are negative.
big_list = [ 17, -72, 97, -18, 32, -15, -63, -57, 40, 83,
-48, 26, 12, -62, 16, 49, 55, -77, -30, 92,
34, -29, -75, 13, 40, -85, 62, -74, -69, -31]
Assume that we wish to sum the absolute values of the numbers in big_list
. We can do so using a for loop and the abs()
value function.
total = 0
for i in range(0, len(big_list)):
total += abs(big_list[i])
print(total)
1473
There are occasions when we might want to create a new list based on the values in one or more already existing lists. Depending on the task, we might be able to accomplish it by starting with an empty list, and then appending elements to it as we loop over another list.
As an example, assume that we have been provided with two equally sized lists, listA
and listB
, as follows:
listA = [13, 18, 23, 42, 27, 22, 36, 17, 44, 34, 35, 33, 41, 43, 12, 45, 29, 37, 14, 15]
listB = [42, 14, 31, 39, 40, 48, 47, 36, 28, 32, 11, 27, 16, 17, 34, 33, 46, 22, 26, 15]
Assume that we need to create a new list, listC
, that has the same number of elements as listA
and listB
, such that an particular element in listC
is the sum of the numbers with the same index in listA
and listB
. The cell below includes code for accomplishing such a task.
listC = []
M = min(len(listA), len(listB))
for i in range(0, M):
temp = listA[i] + listB[i]
listC.append(temp)
print(listC)
[55, 32, 54, 81, 67, 70, 83, 53, 72, 66, 46, 60, 57, 60, 46, 78, 75, 59, 40, 30]