<< Hide Menu
Minna Chow
Milo Chang
Minna Chow
Milo Chang
On the AP exam, you'll be asked to evaluate some basic operations on lists.
** Remember, the AP Pseudocode's index starts at 1.**
grocery_list = ["milk", "eggs", "cheese"]
print (grocery_list[0])
The code's output:
milk
grocery_list = ["milk", "eggs", "cheese"]
change = "soap"
grocery_list[2] = change
print (grocery_list)
The code's output: ["milk", "eggs", "soap"]
grocery_list = ["milk", "eggs", "cheese"]
grocery_list[2] = "fish"
print (grocery_list)
The code's output: ["milk", "eggs", "fish"]
grocery_list = ["milk", "eggs", "cheese"]
grocery_list[0] = grocery_list[2]
print (grocery_list)
The code's output: ["cheese", "eggs", "cheese"]
grocery_list = ["milk", "eggs", "cheese"]
grocery_list.insert (2, "butter")
print (grocery_list)
The code's output: ["milk", "eggs", "butter", "cheese"]
grocery_list = ["milk", "eggs", "cheese"]
grocery_list.append ("flour")
print (grocery_list)
The code's output: ["milk", "eggs", "butter", "flour"]
In Python, you remove items based on element value rather than index number.
grocery_list = ["milk", "eggs", "cheese"]
grocery_list.remove ("eggs")
print (grocery_list)
The code's output: ["milk", "cheese"]
grocery_list = ["milk", "eggs", "cheese"]
print (len (grocery_list))
The code's output: 3
You can also use loops to traverse, or go through, a list. This can either be a complete traversal or a partial traversal, depending on what your loop specifies.
Linear search or sequential search algorithms check each element of a list, in order, until the desired value is found or all elements in the list have been checked.
In Python, you can perform a complete traversal of a list using either a for loop or a while loop. Both implementations are shown below.
grocery_list = ["milk", "eggs", "cheese"]
# for loop implementation
for element in grocery_list:
print(element)
The code's output:
milk
eggs
cheese
grocery_list = ["milk", "eggs", "cheese"]
# while loop implementation
i = 0
while i < len(grocery_list):
print(grocery_list[i])
i += 1
The code's output:
milk
eggs
cheese
In Python, you can also perform a partial traversal of a list using either a for loop or a while loop. Both implementations are shown below.
grocery_list = ["milk", "eggs", "cheese", "apples"]
# for loop implementation
start_index = 1
end_index = 3
for i in range(start_index, end_index + 1):
print(grocery_list[i])
The code's output:
eggs
cheese
apples
grocery_list = ["milk", "eggs", "cheese", "apples"]
# while loop implementation
i = 1
while i < 4:
print(grocery_list[i])
i += 1
The code's output:
eggs
cheese
apples
© 2024 Fiveable Inc. All rights reserved.