Nested List

  • row, column
mylist = [[1,3,5], [34, 67, 92], [-1,3,56, 709, 4560]]
print(mylist[1])
print(mylist[2][3])
mylist[0][0] = -98
print(mylist)
for row in mylist:
    print(row)

List comprehension

new_list = [expression for loop_variable_name in iterable]

  • expression must return a value
mylist = [[1,3,5], [34, 67, 92], [-1,3,56, 709, 4560]]
newlist = [ sum(row) for row in mylist]
print(newlist)
# what is this doing?
another = ["cat dog", "a b c",  "what is this"]
new2dlist = [str.split() for str in another]
print(new2dlist)

Another interesting example

numbers = [int(i) for i in input('Enter numbers:').split()]
print(numbers)

[x ** 2 for x in range(10)]

Data structures

  • organizing data in an organized way
from pprint import pprint

grades = {
   'Sue': {
       'Homeworks': [79, 80, 74],
       'Midterm': 85,
       'Final': 92
   },
   'Bob': {
       'Homeworks': [90, 92, 65],
       'Midterm': 87,
       'Final': 75
   },
   'Sam': {
       'Homeworks': [50, 52, 78],
       'Midterm': 40,
       'Final': 65
   },
}
# notice pretty print
pprint(grades)

How to access data?

final = grades["Sue"]["Final"]
total = 0
for hw in grades["Sue"]["Homeworks"]:
    total += hw

PA 2 Data Structures

word_dicts is the main data structure and is a list of tuples.
process_args() in file words_main.py builds and returns word_dicts

  • each tuple is (str, dict) (one tuple per file)
    • the str is the name of the collection
    • dict is created by categorize_words()

process_word_file() : called per file

  • returns two strings: name of collection and the remainder of the file

categorize_words() : called with a list of valid unique words

  • returns: dictionary {int:list} where int is the length of a word and list is all words of that length

Remember collection_menu()? It uses word_dicts