3.8 & 3.10

Lists

Lists: a sequence of variables

  • we can use lists to store multiple items into one variable
  • used to store collections of data
  • changeable, ordered, allow duplicates

List examples in Python, JavaScript, and Pseudocode.

fruits = ["apple", "grape", "strawberry"]
print (fruits)
const fruits = ["apple", "grape", "strawberry"];
fruits  [apple, grape, strawberry]

More list examples

brands = ["nike", "adidas", "underarmour"] #string
numbers = [1, 2, 3, 4, 5] #integer
truefalse = [True, False, True] #boolean

4 collection data types:

  • 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
  • List: a collection that is ordered, changeable, and allows duplicates

Vocab

  • 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
fruits = ["apple", "grape", "strawberry"]
index = 1

print (fruits[index])
grape

Methods in Lists (What can you do with them?)

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.insert(1, "hockey")
sports.remove("soccer")

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

Don't do this

Iteration is important for your time and sanity

print("alpha")
print("bravo")
print("charlie")
print("delta")
print("echo")
print("foxtrot")
print("golf")
print("hotel")
print("india")
print("juliett")
print("kilo")
print("lima")
print("mike")
print("november")
print("oscar")
print("papa")
print("quebec")
print("romeo")
print("sierra")
print("tango")
print("uniform")
print("victor")
print("whiskey")
print("x-ray")
print("yankee")
print("zulu")
#please help me 
alpha
bravo
charlie
delta
echo
foxtrot
golf
hotel
india
juliett
kilo
lima
mike
november
oscar
papa
quebec
romeo
sierra
tango
uniform
victor
whiskey
x-ray
yankee
zulu

Coding all of these individually takes a lot of unnecessary time, how can we shorten this time?

About Iteration

Iteration is the repetition of a process or utterance applied to the result or taken from a previous statement. There's a lot of types of iteration though, what to use? How do we apply iteration to lists?

Some 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.

There are 2 types of iteration:definite and indefinite. Definite iteration clarifies how many times the loop is going to run, while indefinite specifies a condition that must be met

for variable in iterable: 
    statement()

Iterators, Iterable, and Iteration

  • When an object is iterable it can be used in an iteration
  • When passed through the function iter() it returns an iterator
  • Strings, lists, dictionaries, sets and tuples are all examples of iterable objects.
a = ['alpha', 'bravo', 'charlie']

itr = iter(a)
print(next(itr))
print(next(itr))
print(next(itr))
alpha
bravo
charlie

Loops

  • Well, above is basically just printing them again, so how do we takes these iterators into something we can make use for?
  • Loops take essentially what we did above and automates it, here are some examples.
list = ["Alpha", "Bravo", "Charlie", "Delta", "Echo", "Foxtrot", "Golf", "Hotel", "India", "Juliett", "Kilo", "Lima", "Mike", "November", "Oscar", "Papa", "Quebec", "Romeo", "Sierra", "Tango", "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)
    
Alpha
Bravo
Charlie
Delta
Echo
Foxtrot
Golf
Hotel
India
Juliett
Kilo
Lima
Mike
November
Oscar
Papa
Quebec
Romeo
Sierra
Tango
Uniform
Victor
Whiskey
X-ray
Yankee
Zulu
list = ["Alpha", "Bravo", "Charlie", "Delta", "Echo", "Foxtrot", "Golf", "Hotel", "India", "Juliett", "Kilo", "Lima", "Mike", "November", "Oscar", "Papa", "Quebec", "Romeo", "Sierra", "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
Charlie
Delta
Echo
Foxtrot
Golf
Hotel
India
Juliett
Kilo
Lima
Mike
November
Oscar
Papa
Quebec
Romeo
Sierra
Tango
Uniform
Victor
Whiskey
X-ray
Yankee
Zulu
list = ["Alpha", "Bravo", "Charlie", "Delta", "Echo", "Foxtrot", "Golf", "Hotel", "India", "Juliett", "Kilo", "Lima", "Mike", "November", "Oscar", "Papa", "Quebec", "Romeo", "Sierra", "Tango", "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
Alpha
Bravo
Charlie
Delta
Echo
Foxtrot
Golf
Hotel
India
Juliett
Kilo
Lima
Mike
November
Oscar
Papa
Quebec
Romeo
Sierra
Tango
Uniform
Victor
Whiskey
X-ray
Yankee
Zulu

range() function

  • Need to save even more time? The above is useful for many occasions, but can get tedious fast, in this case, use range()
x = range(5)

for n in x:
    print(n)
0
1
2
3
4

Else, elif, and break

For when 1 statement isn't enough

  • Else:when the condition does not meet, do statement()- Elif: when the condition does not meet, but meets another condition, do statement()
  • Break: stop the loop

Iteration HOMEWORK

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 = {
    "a" : "alpha",
    "b" : "bravo",
    "c" : "charlie",
    "d" : "delta",
    "e" : "echo",
    "f" : "foxtrot",
    "g" : "golf",
    "h" : "hotel",
    "i" : "india",
    "j" : "juliett",
    "k" : "kilo",
    "l" : "lima",
    "m" : "mike",
    "n" : "november",
    "o" : "oscar",
    "p" : "papa",
    "q" : "quebec",
    "r" : "romeo",
    "s" : "sierra",
    "t" : "tango",
    "u" : "uniform",
    "v" : "victor",
    "w" : "whiskey",
    "x" : "xray",
    "y" : "yankee",
    "z" : "zulu"
    }

inp = input()
inpReady = [*inp.lower()]

print(inp)
print(" ")
for i in inpReady:
    if i in words:
        print(words[i])
hello world
 
hotel
echo
lima
lima
oscar
whiskey
oscar
romeo
lima
delta

2D Iteration

2D Arrays

A 2D array is simply just a list of lists. The example below is technically correct but...

keypad = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [" ", 0, " "]]

Conventially 2D arrays are written like below. This is because 2D arrays are meant to be read in 2 dimensions (hence the name). Writing them like below makes them easier to visualize and understand.

keypad =   [[1, 2, 3],
            [4, 5, 6],
            [7, 8, 9],
            [" ", 0, " "]]

Printing a 2D Array

We already know that we can't just print the matrix by calling it. We need to iterate through it to print it.

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   

More Functions

Try to find another way to print the matrix. Only complete one of the two (unless you'd like to do both). Below is a hint

fruit = ["apples", "bananas", "grapes"]
print(fruit)
print(*fruit) # Python built in function: "*". Figure out what it does
['apples', 'bananas', 'grapes']
apples bananas grapes

2D Hack 1

keypad =   [[1, 2, 3],
            [4, 5, 6],
            [7, 8, 9],
            [" ", 0, " "]]

# I had to add keypad back here because it couldn't reference the one that was stated in a few cells above

def print_matrix3(matrix):
    for row in matrix:
        print(*row)

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

Alternatively, find a way to print the matrix using the iter() function you already learned. Or use both!

2D Hack 2

def print_matrix4(matrix):
    matrix_iter = iter(matrix)
    for x in range(len(matrix)):
        inner_matrix_iter = iter(next(matrix_iter))
        for y in matrix[x]:
            print(str(next(inner_matrix_iter)), end=" ")
        print()

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

Birthmonth and Age Hack

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", ",", ".", "/"]]

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", ",", ".", "/"]]

month = keyboard[2][1] + keyboard[1][2] + keyboard[1][9] + keyboard[1][4] + keyboard[1][2] + keyboard[3][6] + keyboard[3][4] + keyboard[1][2] + keyboard[1][3]
age = str(keyboard[0][1]) + str(keyboard[0][7])


print("My birth month: " + month[:1] + month[1:].lower())
print("My age: " + age)
My birth month: September
My age: 17

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)

DO NOT HARD CODE THIS. Don't make it harder on yourself, iterate through, make it abstract so it can be used dynamically. You should be able to input any string and your code should work.

# Here's an attempt. Ran out of time though

def print_matrix1(matrix): 
    for i in range(len(matrix)):
                for j in range(len(matrix[i])):
                    print(matrix[i][j], end=" ")
                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

def fun(x, y):
    month = str(x).lower() + str(y).lower()
    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", ",", ".", "/"]]

    clearedKeyboard = [["`", 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", ",", ".", "/"]]

    for x in month:
        for y in range(len(keyboard)):
            for z in range(len(keyboard[y])):
                if x == str(keyboard[y][z]).lower():
                    keyboard[y][z] = " "


    for x in range(len(keyboard)):
        for y in range(len(keyboard[x])):
            if keyboard[x][y] != " ":
                keyboard[x][y] = " "
            else:
                keyboard[x][y] = clearedKeyboard[x][y]


    print_matrix1(fun)

fun("September", 1)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/home/azeemk/vscode/fastpages-project/_notebooks/2022-12-05-studentTeaching8-10.ipynb Cell 51 in <cell line: 38>()
     <a href='vscode-notebook-cell://wsl%2Bubuntu/home/azeemk/vscode/fastpages-project/_notebooks/2022-12-05-studentTeaching8-10.ipynb#Y101sdnNjb2RlLXJlbW90ZQ%3D%3D?line=32'>33</a>                 keyboard[x][y] = clearedKeyboard[x][y]
     <a href='vscode-notebook-cell://wsl%2Bubuntu/home/azeemk/vscode/fastpages-project/_notebooks/2022-12-05-studentTeaching8-10.ipynb#Y101sdnNjb2RlLXJlbW90ZQ%3D%3D?line=35'>36</a>     print_matrix1(fun)
---> <a href='vscode-notebook-cell://wsl%2Bubuntu/home/azeemk/vscode/fastpages-project/_notebooks/2022-12-05-studentTeaching8-10.ipynb#Y101sdnNjb2RlLXJlbW90ZQ%3D%3D?line=37'>38</a> fun("September", 1)

/home/azeemk/vscode/fastpages-project/_notebooks/2022-12-05-studentTeaching8-10.ipynb Cell 51 in fun(x, y)
     <a href='vscode-notebook-cell://wsl%2Bubuntu/home/azeemk/vscode/fastpages-project/_notebooks/2022-12-05-studentTeaching8-10.ipynb#Y101sdnNjb2RlLXJlbW90ZQ%3D%3D?line=31'>32</a>         else:
     <a href='vscode-notebook-cell://wsl%2Bubuntu/home/azeemk/vscode/fastpages-project/_notebooks/2022-12-05-studentTeaching8-10.ipynb#Y101sdnNjb2RlLXJlbW90ZQ%3D%3D?line=32'>33</a>             keyboard[x][y] = clearedKeyboard[x][y]
---> <a href='vscode-notebook-cell://wsl%2Bubuntu/home/azeemk/vscode/fastpages-project/_notebooks/2022-12-05-studentTeaching8-10.ipynb#Y101sdnNjb2RlLXJlbW90ZQ%3D%3D?line=35'>36</a> print_matrix1(fun)

/home/azeemk/vscode/fastpages-project/_notebooks/2022-12-05-studentTeaching8-10.ipynb Cell 51 in print_matrix1(matrix)
      <a href='vscode-notebook-cell://wsl%2Bubuntu/home/azeemk/vscode/fastpages-project/_notebooks/2022-12-05-studentTeaching8-10.ipynb#Y101sdnNjb2RlLXJlbW90ZQ%3D%3D?line=2'>3</a> def print_matrix1(matrix): 
----> <a href='vscode-notebook-cell://wsl%2Bubuntu/home/azeemk/vscode/fastpages-project/_notebooks/2022-12-05-studentTeaching8-10.ipynb#Y101sdnNjb2RlLXJlbW90ZQ%3D%3D?line=3'>4</a>     for i in range(len(matrix)):
      <a href='vscode-notebook-cell://wsl%2Bubuntu/home/azeemk/vscode/fastpages-project/_notebooks/2022-12-05-studentTeaching8-10.ipynb#Y101sdnNjb2RlLXJlbW90ZQ%3D%3D?line=4'>5</a>                 for j in range(len(matrix[i])):
      <a href='vscode-notebook-cell://wsl%2Bubuntu/home/azeemk/vscode/fastpages-project/_notebooks/2022-12-05-studentTeaching8-10.ipynb#Y101sdnNjb2RlLXJlbW90ZQ%3D%3D?line=5'>6</a>                     print(matrix[i][j], end=" ")

TypeError: object of type 'function' has no len()

If you get stuck you can just make a picture with an array and print it (I will grade based on how good it looks)

I do expect an attempt so write some code to show you tried the challenge.