A Python list is an ordered and changeable collection of data objects. Unlike an array, which can contain objects of a single type, a list can contain a mixture of objects. They start from 0. (The 1st element would actually be the 0th element)
List Functions
Creating a list:
In order to create a list named “aList”, type aList = []. This creates an empty list. A list with elements would look like this aList = [element1,element2,element3]
Append:
In Python, the append() method is used to add an element to the end of a list. The element in the parenthesis is what is added to the list.
# College Board Pseudo Code
aList ← []
USER_INPUT ← ("Enter an item you want (or 'q' to quit): ")
REPEAT UNTIL USER_INPUT ← q{
APPEND (aList, USER_INPUT)
}
DISPLAY(aList)
aList = []
while True:
user_input = input("Enter an item you want (or 'q' to quit): ")
if user_input.lower() == 'q':
break
aList.append(user_input)
print("Things You Want:", aList)
Things You Want: ['1', 'item', '2']
Accessing an element:
In order to access a specific element from a list, you would put the element in []. For example, If I had to access the third element in the list aList, I would say “aList[2]”.
# College Board Pseudo Code
aList ← []
USER_INPUT ← ("Enter an item you want (or 'q' to quit): ")
REPEAT UNTIL USER_INPUT ← q{
APPEND (aList, USER_INPUT)
}
DISPLAY(aList[2])
aList = []
while True:
user_input = input("Enter an item you want (or 'q' to quit): ")
if user_input.lower() == 'q':
break
aList.append(user_input)
print("The Second thing on your list is", aList[1])
print(aList)
The Second thing on your list is 3
['2', '3', '6', 'hunt']
Deleting an element:
In order to delete an element, choose the element the same way you would access it but put “del” before it. For example, If I had to delete the third element in a list called aList, I would say “del aList[2]”.
# College Board Pseudo Code
aList ← []
USER_INPUT ← ("Enter an item you want (or 'q' to quit): ")
REPEAT UNTIL USER_INPUT ← q{
APPEND (aList, USER_INPUT)
}
REMOVE (aList, 2)
DISPLAY(aList)
aList = []
while True:
user_input = input("Enter an item you want (or 'q' to quit): ")
if user_input.lower() == 'q':
break
aList.append(user_input)
print("This is your list: ", aList)
del aList[1]
print("This is your new list: ", aList)
This is your list: ['5', '4', '4']
This is your new list: ['5', '4']
Create a list (with user input) using objects with different types. Remove the first element from the list and print the list.
# Code goes here:
arr = []
keep_going = 'Y'
while keep_going == 'Y':
arr.append(input("Add an input: "))
keep_going = input("Would you like to keep going? [Y/N] ").upper()
print(f"Before deletion: {arr}")
del arr[0]
print(f"After deletion: {arr}")
Before deletion: ['6', '3']
After deletion: ['3']
Assigning a value:
To assign the values a list named bList to aList of one list to another you simply have to do aList = bList.
Length of a list:
To get the length of a list named aList, you just need to do len(aList). This gives you the number of elements in a list.
aList = ["Yeezys","Yeezys"]
bList = ["No Yeezys"]
bList = aList
list_length = len(bList)
print("Things I want:", bList)
print("How many yeezys:",list_length)
Things I want: ['Yeezys', 'Yeezys']
How many yeezys: 2
For each item in a list:
If you want to do something to each item in a list, you will need to use this. an example of it is shown below.
my_list = [1, 2, 3, 4, 5]
print("Original List:", my_list)
for i in range(len(my_list)):
my_list[i] += 1
print("Modified List:", my_list)
print("Length of the list:", len(my_list))
Original List: [1, 2, 3, 4, 5]
Modified List: [2, 3, 4, 5, 6]
Length of the list: 5
Create a new list that modifies the original list by multiplying each element by 2 and prints the length of the list.
my_list = [1, 2, 3, 4, 5]
print("Original List:", my_list)
arr = [i*2 for i in my_list]
print(f"New list: {arr}")
print(f"Length of list: {len(arr)}")
# Code goes here:
Original List: [1, 2, 3, 4, 5]
New list: [2, 4, 6, 8, 10]
Length of list: 5
A search algorithm is an algorithm that retrieves information stored in a data structure or calculated in the search space of a problem domain, with either discrete or continuous values.
Linear Search
The most basic way of searching in which each element is searched in the order it appears in the list. The list doesn’t need to be organized.
For the code given below, the algorithm compares each value to the previous value, and if the value is smaller than the previous value, that value becomes the new min. The algorithm continues until it reaches the end of the list.
nums[] ← [86, 75, 98, 100, 71, 65, 84]
min ← nums[0]
FOR EACH score IN nums[] DO
IF score < min THEN
min ← score
END IF
END FOR
OUTPUT "The minimum value in the list is:", min
nums = [86, 75, 98, 100, 71, 65, 84]
print(nums)
min = nums[0]
for score in nums:
if (score < min):
min = score
print("The minimum value in the list is:", min)
[86, 75, 98, 100, 71, 65, 84]
The minimum value in the list is: 65
Create a linear search algorithm that determines the maximum value in a list.
nums = [86, 75, 98, 100, 71, 65, 84]
print(nums)
# Code goes here:
for num in nums:
if num == nums[0]:
max = num
else:
if num > max:
max = num
print(f"The number with the highest value in this list is {max}")
[86, 75, 98, 100, 71, 65, 84]
The number with the highest value in this list is 100
Binary Search
A binary search, also known as half-interval search, logarithmic search, or binary chop is a search algorithm that finds the position of a target value within a sorted array.
How does Binary Search work:
- Binary search works on sorted arrays.
- Binary search begins by comparing an element in the middle of the array with the target value.
- If the target value matches the element:
- Its position in the array is returned and exit the program.
- If the target value is less than the element:
- The search continues in the lower half of the array. Go to Step-2
- If the target value is greater than the element, the search continues in the upper half of the
array. Go to Step-2
- Go back to Step-2
# Returns index of x in arr if present, else -1
def binary_search(arr, low, high, x):
# Check base case
if high >= low:
mid = (high + low) // 2
# If element is present at the middle itself
if arr[mid] == x:
return mid
# If element is smaller than mid, then it can only
# be present in left subarray
elif arr[mid] > x:
return binary_search(arr, low, mid - 1, x)
# Else the element can only be present in right subarray
else:
return binary_search(arr, mid + 1, high, x)
else:
# Element is not present in the array
return -1
# Test array
arr = [ 2, 3, 4, 10, 40 ]
x = 10
# Function call
result = binary_search(arr, 0, len(arr)-1, x)
if result != -1:
print("The Element is in index", str(result))
else:
print("Element is not present in array")
The Element is in index 3
#
Usually used to denote how much run time an algorithm takes or how much memory is used by an algorithm.
In our case we are using it to show how many tries it will take for a search algorithm to find something.
Linear Search vs Binary Search big O notation:
- Linear search complexity is denoted by O(n) as every element in the array is compared only once.
- In linear search, best-case complexity is O(1) where the element is found at the first index.
- Worst-case complexity is O(n) where the element is found at the last index or the element is not present in the array.
- Binary search, best-case complexity is O(1) where the element is found at the middle index. The worst-case complexity is O(log base 2 n).
Create a binary search algorithm that sorts for the value 25.
nums = [num for num in range(1, 101)]
# Code goes here:
target = int(input("Enter a number between 1 and 100: "))
def guessing_game(arr, target):
left, right = 0, len(arr) - 1
tries = 1
while left <= right:
mid = left + (right - left) // 2
if arr[mid] == target:
return (f"Your number was {mid + 1} and it took {tries} tries to get it!")
elif arr[mid] < target:
left = mid + 1
tries += 1
else:
right = mid - 1
tries += 1
return -1
result = guessing_game(nums, target)
if result != -1:
print(result)
else:
print(f"Element {target} is not found in the list.")
Your number was 69 and it took 6 tries to get it!