Complete the code to print all elements in the array using a for loop.
arr = [10, 20, 30, 40] for [1] in arr: print([1])
The variable x is used to represent each element in the array during traversal.
Complete the code to print elements at even indices of the array.
arr = [5, 10, 15, 20, 25] for i in range(0, len(arr), [1]): print(arr[i])
Using a step of 2 in range allows traversal of even indices: 0, 2, 4, ...
Fix the error in the code to print elements in reverse order.
arr = [1, 2, 3, 4, 5] for i in range(len(arr)-1, [1], -1): print(arr[i])
The stop value in range is exclusive, so to include index 0 when traversing backwards, use -1 as stop. This generates indices 4, 3, 2, 1, 0.
Fill both blanks to create a dictionary with elements as keys and their indices as values.
arr = ['a', 'b', 'c'] index_map = [1] for [2] in range(len(arr))}
The dictionary comprehension uses {arr[i]: i for i in range(len(arr))} to map elements to indices.
Fill all three blanks to create a list of squares of even numbers from the array.
arr = [1, 2, 3, 4, 5, 6] squares = [[1] for [2] in arr if [3] % 2 == 0]
The list comprehension squares each x in arr only if x is even.