"OIM3640: GitHub settings"
def
return
print()
if
elif
else
for
while
break
continue
prices = {'AAPL': 260.81, 'NVDA': 186.00, 'MSFT': 404.88, 'GOOG': 308.42}
'AAPL'
prices['TSLA']
$200
get()
def histogram(s): d = {} for c in s: d[c] = d.get(c, 0) + 1 return d result = histogram('bookkeeper') print(result['o']) print(result.get('o', 0)) print(result.get('z', 0))
Try these puzzles at pythonchallenge.com:
2 ** 38
Work in pairs. See how far you get in 10 minutes!
What we'll learn:
zip()
t = ('a', 'b', 'c', 'd') t[0] # 'a' t[1:3] # ('b', 'c') len(t) # 4
But you cannot modify them:
t[0] = 'X' # TypeError! Tuples are immutable.
Like strings, unlike lists.
# Swap two variables without a temp a, b = b, a # Unpack a tuple into variables point = (3, 4) x, y = point # x = 3, y = 4
Works great with dict.items():
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.
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)) # {'AAPL': 182.30, 'GOOG': 141.80, 'MSFT': 415.20}
A set holds unique items only, unordered:
fruits = {'apple', 'banana', 'apple', 'cherry'} print(fruits) # {'apple', 'banana', 'cherry'} len(fruits) # 3
Useful for removing duplicates:
nums = [1, 2, 2, 3, 3, 3] unique = set(nums) # {1, 2, 3} len(set(nums)) # 3 unique values
a = {1, 2, 3, 4} b = {3, 4, 5, 6} a & b # {3, 4} intersection a | b # {1, 2, 3, 4, 5, 6} union a - b # {1, 2} difference
Check membership (very fast!):
3 in a # True
Sets are great when you need fast lookup or uniqueness.
str
list
tuple
dict
set
* Dicts preserve insertion order (Python 3.7+).
is_anagram
is_palindrome
reverse_sentence
total_length
value_counts
has_duplicates
find_repeats
add_counters
is_interlocking
shift_word
most_frequent_letters
word_distance
zip
Questions? Ask now!
logs/wk08.md
Next session: Text Analysis and Generation
global styles