Lists and Iterations

Lists

  • Sequence of variables
  • used rto store multiple items in a variable
  • Ordered and flexible
sports = ["football", "hockey", "baseball", "basketball"]

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

# add "golf" as the 3rd element in the list
print (sports)
['football', 'soccer', 'golf', 'basketball']

Iterations

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.

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 Functions

SAVES MORE TIME!

x = range(5)

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

2D Iterations

A 2D array is simply just a list of lists. The example below is technically correct but 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, " "]]

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

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 HW Iteration 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

  • check TABLe

Lists are just one of four collection data 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 Terms

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

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:  
        for col in row:  
            print(col, end=" ") 
        print()
keypad = [[1, 2, 3],
            [4, 5, 6],
            [7, 8, 9],
            [" ", 0, " "]]
print_matrix2(keypad)
1 2 3 
4 5 6 
7 8 9 
  0   

apples and bananas example

fruit = ["apples", "bananas", "grapes"]
print(fruit)
print(*fruit) 
['apples', 'bananas', 'grapes']
apples bananas grapes
def print_matrix3(matrix):
    for row in matrix:
        print(*row)

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

another way of making keypad

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

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

keyboard

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 = "DECEMBER16"
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
DECEMBER16

challenge

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 = "DECEMBER16"
for row in keyboard: 
    for key in row: 
        if str(key) in output: 
            print(key, end='')
        else:
            print(" ", end='')
    print("\n")
 1    6      

  ER        

  D        

  C B M