Vocab

  • Lists: sequence of variables
  • Index: a term used to sort data in order to reference to an element in a list (allows for duplicates)
  • Elements: the values in the list assigned to an index

Boolean Iteration and Lists

  • Lists
    • sequence of variables
    • used to store multiple items into a single variable
    • changeable, allow duplicates
    • can hold integers, strings, or booleans
  • Lists are 1/4 types of data collection types in python
    • Tuple: collection that is ordered, unchangeable, allows duplicates
    • Set: collection that is unordered, unchangeable, doesn't allow duplicates
    • Dictionary: collection that is ordered, changeable, doesn't allow duplicates
  • Index: a term used to sort data in order to reference to an element in a list (allows for duplicates)
  • Elements: the values in the list assigned to an index
  • Iteration: repetition of a process or utterance applied to the result or taken from a previous statement
  • Loops: automate the iteration process
fruits = ["apple", "grape", "strawberry"]
index = 1

print (fruits[index])
grape

Methods in Lists

Method Definition Example
append() adds element to the end of the list fruits.append("watermelon")
index() returns the index of the first element with the specified value fruits.index("apple")
insert() adds element at given position fruits.insert(1, "watermelon")
remove() removes the first item with the specified value fruits.remove("strawberry")
reverse() reverses the list order fruits.reverse()
sort() sorts the list fruits.sort()
count() returns the amount of elements with the specified value fruits.count("apple")
copy() returns a copy of the list fruits.copy()
clear() removes the elements from the list fruits.clear()
sports = ["football", "soccer", "baseball", "basketball"]

# change the value "soccer" to "hockey"
sports.remove("soccer")
sports.insert(1, "hockey")
print (sports)
['football', 'hockey', 'baseball', 'basketball']
sports = ["football", "soccer", "baseball", "basketball"]

# add "golf" as the 3rd element in the list
sports.insert(2, "golf")
print (sports)
['football', 'soccer', 'golf', 'baseball', 'basketball']
  • Iteration
    • repetition of a process or utterance applied to the result or taken from a previous statement
    • methods include using a "for loop", using a "for loop and range()", using a "while loop", and using comprehension
    • Lists, tuples, dictionaries, and sets are iterable objects. They are the 'containers' that store the data to iterate
    • Each of these containers are able to iterate with the iter() command.
    • 2 types
      • Definite: clarifies how many times the loop is going to run
      • Indefinite: specifies a condition that must be met
  • Loops
    • automates the iteration process
list = ["Uniform", "Victor", "Whiskey", "X-ray", "Yankee", "Zulu"]

# using a for loop 
for i in list:
    #for item in the list, print the item 
    print(i)
Uniform
Victor
Whiskey
X-ray
Yankee
Zulu
list = ["Alpha", "Bravo", "Tango", "Uniform", "Victor", "Whiskey", "X-ray", "Yankee", "Zulu"]

# Taking the length of the list 
lengthList = len(list) 

# Iteration using the amount of items in the list
for i in range(lengthList):
    print(list[i])
Alpha
Bravo
Tango
Uniform
Victor
Whiskey
X-ray
Yankee
Zulu
list = ["Uniform", "Victor", "Whiskey", "X-ray", "Yankee", "Zulu"]

# Once again, taking the length of the list
lengthList = len(list)

# Setting the variable we are going to use as 0
i=0 

# Iteration using the while loop 
# Argument saying WHILE a certain variable is a certain condition, the code should run
while i < lengthList:
    print(list[i])
    i += 1
Uniform
Victor
Whiskey
X-ray
Yankee
Zulu
  • 2D Iterations
    • list of lists
keypad = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [" ", 0, " "]]
  • Printing a 2D array
def print_matrix1(matrix): 
    for i in range(len(matrix)):  # outer for loop. This runs on i which represents the row. range(len(matrix)) is in order to iterate through the length of the matrix
        for j in range(len(matrix[i])):  # inner for loop. This runs on the length of the i'th row in the matrix (j changes for each row with a different length)
            print(matrix[i][j], end=" ")  # [i][j] is the 2D location of that value in the matrix, kinda like a coordinate pair. [i] iterates to the specific row and [j] iterates to the specific value in the row. end=" " changes the end value to space, not a new line.
        print() # prints extra line. this is in the outer loop, not the inner loop, because it only wants to print a new line for each row
print("Raw matrix (list of lists): ")
print(keypad)
print("Matrix printed using nested for loop iteration:")
print_matrix1(keypad)
print()
Raw matrix (list of lists): 
[[1, 2, 3], [4, 5, 6], [7, 8, 9], [' ', 0, ' ']]
Matrix printed using nested for loop iteration:
1 2 3 
4 5 6 
7 8 9 
  0   

def print_matrix2(matrix):
    for row in matrix:  # Iterates through each "row" of matrix. Row is a dummy variable, it could technically be anything. It iterates through each value of matrix and each value is it's own list. in this syntax the list is stored in "row".
        for col in row:  # Iterates through each value in row. Again col, column, is a dummy variable. Each value in row is stored in col.
            print(col, end=" ") # Same as 1
        print() # Same as 1

print_matrix2(keypad)
1 2 3 
4 5 6 
7 8 9 
  0   

HW

def print_matrix3(matrix):
     for row in matrix:
        print(*row, end=" ")
        print()

print_matrix3(keypad)
1 2 3 
4 5 6 
7 8 9 
  0   

Print what month you were born and how old you are by iterating through the keyboard (don't just write a string).

keyboard = [["`", 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, "-", "="],
            ["Q", "W", "E", "R", "T", "Y", "U", "I", "O", "P", "[", "]"],
            ["A", "S", "D", "F", "G", "H", "J", "K", "L", ";", "'"],
            ["Z", "X", "C", "V", "B", "N", "M", ",", ".", "/"]]

output = "MAY16"
for char in output: #each item in the output is a character
    for row in keyboard: #each item in the keyboard is a row
        for key in row: #each item in the row is a key
            if str(key) == char: #if the key matches each character in output
                print(key, end='')
                break #ends the loop. back to first loop
MAY16

Use the list below to turn the first letter of any word (using input()) into its respective NATO phonetic alphabet word

Ex: list -> lima india sierra tango

words = ["alfa", "bravo", "charlie", "delta", "echo", "foxtrot", "golf", "hotel", "india", "juliett", "kilo",
"lima", "mike", "november", "oscar", "papa", "quebec", "romeo", "sierra", "tango", "uniform", "victor", "whiskey", "xray", "yankee", "zulu"]

inp = input().lower()

letters = []
for letter in inp: 
    for word in words:
        if word.startswith(letter):
            print(word)
            break
    
victor
india
victor
india
alfa
november

Challenge

  • Change all of the letters that you DIDN'T print above to spaces, " ", and then print the full keyboard. (the things you did print should remain in the same spot)

  • Alternative Challenge: If you would prefer, animate it using some form of delay so it flashes one of your letters at a time on the board in order and repeats. (this one may be slightly more intuitive)

keyboard = [["`", 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, "-", "="],
            ["Q", "W", "E", "R", "T", "Y", "U", "I", "O", "P", "[", "]"],
            ["A", "S", "D", "F", "G", "H", "J", "K", "L", ";", "'"],
            ["Z", "X", "C", "V", "B", "N", "M", ",", ".", "/"]]

output = "MAY16"
for row in keyboard: #each item in the keyboard is a row
    for key in row: #each item in the row is a key
        if str(key) in output: #check if key is in output
            print(key, end='')
        else:
            print(" ", end='')
    print("\n")
 1    6      

     Y      

A          

      M