"OIM3640: GitHub settings"
for
while
break
continue
import yfinance as yf stock = yf.Ticker('AAPL') info = stock.info # a dict! print(info['shortName']) # 'Apple Inc.' print(info['currentPrice']) # 229.87
We'll learn about APIs and libraries later in the course!
info = yf.Ticker('AAPL').info # 'shortName', 'city', 'longBusinessSummary', # 'sector', 'fullTimeEmployees', ...
info['longBusinessSummary'].split()
'iPhone' in info['longBusinessSummary']
info['city'][0] = 'c'
len(info)
info
tickers = ['AAPL', 'NVDA', 'MSFT'] prices = {} for t in tickers: prices[t] = yf.Ticker(t).info['currentPrice']
sorted(tickers)
tickers
'TSLA' in prices
'GOOG'
prices
What we'll learn:
zip()
t = ('a', 'b', 'c', 'd') t[0] # 'a' t[1:3] # ('b', 'c')
You cannot modify them:
t[0] = 'X' # TypeError! Tuples are immutable.
a, b = b, a # swap without a temp! point = (3, 4) x, y = point # x = 3, y = 4 # Works great with dict.items() for key, value in prices.items(): print(f'{key}: ${value}')
Tuples let functions return more than one value:
def min_max(numbers): return min(numbers), max(numbers) lowest, highest = min_max([3, 1, 4, 1, 5]) # lowest = 1, highest = 5
The return creates a tuple; unpacking assigns both at once.
return
You want to track prices by ticker and date:
# Try a list key? prices = {['AAPL', '2026-03-24']: 229} # TypeError! # String key? Works, but messy... prices = {'AAPL(2026-03-24)': 229} # Tuple key ✓ clean and natural! prices = {('AAPL', '2026-03-24'): 229}
names = ['AAPL', 'GOOG', 'MSFT'] prices = [182.30, 141.80, 415.20] for name, price in zip(names, prices): print(f'{name}: ${price}') # Create a dict from two lists stock_prices = dict(zip(names, prices))
A set holds unique items only, unordered:
watchlist = {'AAPL', 'NVDA', 'AAPL', 'MSFT'} print(watchlist) # {'AAPL', 'NVDA', 'MSFT'} tickers = ['AAPL', 'NVDA', 'AAPL', 'MSFT', 'NVDA'] unique = set(tickers) # {'AAPL', 'NVDA', 'MSFT'} len(set(tickers)) # 3 unique stocks
my_stocks = {'AAPL', 'NVDA', 'MSFT', 'GOOG'} your_stocks = {'MSFT', 'GOOG', 'TSLA', 'AMZN'} my_stocks & your_stocks # {'MSFT', 'GOOG'} both own my_stocks | your_stocks # all 6 stocks combined my_stocks - your_stocks # {'AAPL', 'NVDA'} only I own
Membership: 'TSLA' in my_stocks # False
'TSLA' in my_stocks # False
import timeit words = open('data/words.txt').read().split() word_set = set(words) # 113K+ words def search_list(): return 'python' in words def search_set(): return 'python' in word_set print('List:', timeit.timeit(search_list, number=1000)) print('Set: ', timeit.timeit(search_set, number=1000)) # List: 0.8500s Set: 0.0003s
Curious why sets are faster? Ask AI!
str
list
tuple
dict
set
You're building a music app:
('Bohemian Rhapsody', 'Queen', 1975)
Let's practice! All data structures come together:
words = [] for line in open('jekyll.txt'): for word in line.split(): words.append(word.strip().lower()) print(len(words)) # total words print(len(set(words))) # unique words (set!)
freq = {} for word in words: freq[word] = freq.get(word, 0) + 1 def second_element(t): return t[1] top = sorted(freq.items(), key=second_element, reverse=True) for word, count in top[:5]: print(f'{word}: {count}')
Topics: lists, tuples, dicts, sets, mutability, counting pattern
You may bring one cheat sheet (one page, both sides).
Python 3 Cheat Sheet for reference.
Try the text analysis code on a book from Project Gutenberg:
MP2 is about text analysis - take any text, find something interesting. Start with pure Python, then explore libraries. Write your PROPOSAL.md!
PROPOSAL.md
is_anagram
is_palindrome
reverse_sentence
total_length
value_counts
get()
if
has_duplicates
find_repeats
add_counters
is_interlocking
shift_word
most_frequent_letters
word_distance
zip
Questions? Ask now!
logs/wk09.md
Next session: Quiz 2 + File I/O
global styles