1.
Q16: Given the following code, what is the value in
sum after execution?
alpha = [2, 4, 6, 8, 10, 12, 14]
sum = 0
for k in range(0, len(alpha), 2):
sum = sum + alpha[k]
size - 1 elements.
append or insert method is being used on an instance of a list, it is an Adding a Value to a List Element.
listName[index] returns value stored at that index.
0 and len(listName)-1, inclusive, or a negative value; otherwise an IndexError exception occurs at runtime.
listName[startIndex:endIndex] returns a new list containing the elements from startIndex to endIndex-1 (inclusive)
startIndex starts from the beginning of the list, and omitting endIndex goes to the end of the list
[] brackets to determine the index of the element to be changed, and the list to change.
append or insert method is being used. Note that either way you do not use an assignment statement, it is just a method call.
append is used, the new value is added to the end of the list.
insert method to add the new value at the specified index. Existing values starting from that index are shifted to the right.
range(len(list_name)), then the list is being traversed by index. The range function can either take one argument (the length of the list) or 3 arguments (the starting index, ending index, and step size). If the range function takes one argument, it will start at 0 and go to the length of the list - 1. If the range function takes 3 arguments, it will start at the first argument and go to the second argument - 1, incrementing by the third argument. Otherwise, if range is not used, then the list is being traversed by value.
append or insert methods. The append method adds a new value to the end of the list, while the insert method adds a new value at the specified index. Existing values starting from that index are shifted to the right.
sum after execution?
alpha = [2, 4, 6, 8, 10, 12, 14]
sum = 0
for k in range(0, len(alpha), 2):
sum = sum + alpha[k]
sum after execution?
beta = []
sum = 0
for i in range(0, 5):
beta.append(i * 2 + 1)
for i in range(1, len(beta)):
sum += beta[i]