Essential Python
Overview of the Most Crucial Functions
String Methods
Let s = “Hello, world!” and b = b“Hello, world!”
● Case conversion
○ s.lower(); s.upper(); s.capitalize(); s.title(); s.swapcase()
● Predicates
○ s.islower(); s.isupper(); s.isspace(); s.isdigit(); s.isalpha(); s.isprint()
● Splitting, counting, combining
○ s.split() → list; s.join(list) → str; s.find(str) → int; s.count(str) → int
● Convert between strings and bytes 2
Lists and List Operations
● Empty list
○ [] or list()
● Non-empty list
○ l1 = [“Mary”, “had”, “a”, “little”, “lamb”]; l2 = [1, 2, 3.14]; l3 = [[1,2,3.14], [“Mary”, “had”]]
● List indexing
○ l1[0] → “Mary”; l2[-1] = 3; l2[2] → 3; l3[0][0] → “Mary”; l3[-1][-1][-1] → “d”
● List alternation
○ l1.append(item) → None; l1.extend(list) → None; l1.sort() → None; l1.remove(item) → None 3
● Empty tuple
○ (,) or tuple()
● Non-empty tuple
○ t1 = (“Mary”, “had”, “a”, “little”, “lamb”); t2 = (1, 2, 3.14); t3 = ([1,2,3.14], [“Mary”, “had”])
● Tuple indexing
○ t1[0] → “Mary”; t2[-1] = 3; t2[2] → 3.14; t3[0][0] → “Mary”; t3[-1][-1][-1] → “d”
● Other tuple operations
○ t1.count(item) → int; t1.index(item) → item
Tuples and Tuple Operations
4
IMMUTABLE!
Dictionaries and Dictionary Operations
● Empty dictionary
○ {} or dict()
● Non-empty dictionary
○ d = {“Mary” : 1, “had” : 2, “a” : 3, “little” : 4, “lamb” : 5}; d = dict([(“Mary”, 1), (“had”, 2), (“a”, 3)])
● Dictionary indexing
○ d[“Mary”] → 1; d[“lamb”] = None; d[“lamb”] → None
● Dictionary alternation
○ d.update({key:value}) → None; d[newkey]=newvalue; del d[key] 5
All keys must be different and
immutable.
Sets and Set Operations
● Empty set
○ set()
● Non-empty set
○ s = set([“Mary”, “had”, “a”, “little”, “lamb”])
● Set alternation
○ s.add(item) → set; s.remove(item) → set; s.clear() → set
● Set theoretic operations
○ s1 | s2 → union of sets; s1 & s2 → intersection of sets; s1 - s2 → difference of sets 6
Cannot be indexed. All elements
unique.
Generator Functions (“lazy” functions)
● Produce one item at a time; more efficient that lists
● Most common generators:
○ range(x=0,y,z=1) → numbers from y (inclusive) to x (not inclusive) with step z
○ enumerate(l) → tuples (0, l[0]), (1, l[1]), (2, l[2]), …
○ zip(l1, l2) → tuples (l1[0], l2[0]), (l1[1], l2[1]), (l2[1], l2[2]), …
● Lists and dictionaries from generators:
○ list(range(n)); list(enumerate(items)); list(zip(first_items, second_items))
○ dict(enumerate(values)); dict(zip(keys, values))
7
List Comprehensions
● A concise and powerful way of running a “foreach” loop
○ result = [action(item) for item in collection if condition(item)]
Apply action() to each item in the collection (string, list, set, tuple, dictionary), for which the
condition is True, and collect the results into a list. The condition is optional (default: True).
● Examples:
○ [c.upper() for c in “Hello, world!”] → list of upper-cased characters
○ “”.join([c for c in “Mary had a little lamb”] if c not in “aouie”]) → string with removed vowels
○ [x**2 for x in range(10) if x % 3 == 0] → list of squares if divisible by 3
○ [key[0] for key in some_dict] → list of first characters of all keys
8
Cool Idioms
● Remove duplicates from list l
○ list(set(l))
● Remove multiple spaces from string s
○ “ ”.join(s.split())
● Swap keys and values in dictionary d (duplicate value will be removed)
○ dict([(v,k) for (k,v) in d.items()])
● Nested list comprehension: read all lines from file and remove all leading and
trailing white spaces and empty lines
9
Counters
● Creation
○ from collections import Counter
○ cntr = Counter(any_collection) → Counter object
● Use
○ freqs.most_common(n=all) → list of tuples (item, frequency), ordered by decreasing frequency
○ cntr = Counter(‘mary had a little lamb’)
○ cntr.most_common(5) → [(' ', 4), ('a', 4), ('l', 3), ('m', 2), ('t', 2)]
● Frequency dictionary
10
Files
● Opening
○ infile = open(name, “r”); outfile = open(name, “w”); outfile_with_append = open(name, “a”)
○ bin_infile = open(name, “rb”); bin_outfile = open(name, “wb”)
● Closing
○ infile.close(); outfile.close()
○ with open(name, mode) as file_handle:
do_something(file_handle) # No need to close the file!
● Reading:
○ infile.read(n=all) → string of at most n characters; bin_infile(n=all) → at most n bytes
11
URLs and Exceptions
import urllib.request, sys
url = “http://networksciencelab.com”
try:
page = urllib.request.urlopen(url)
html = page.read() # 😊
except:
print() # 😞
sys.exit(1)
12

Python overview

  • 1.
    Essential Python Overview ofthe Most Crucial Functions
  • 2.
    String Methods Let s= “Hello, world!” and b = b“Hello, world!” ● Case conversion ○ s.lower(); s.upper(); s.capitalize(); s.title(); s.swapcase() ● Predicates ○ s.islower(); s.isupper(); s.isspace(); s.isdigit(); s.isalpha(); s.isprint() ● Splitting, counting, combining ○ s.split() → list; s.join(list) → str; s.find(str) → int; s.count(str) → int ● Convert between strings and bytes 2
  • 3.
    Lists and ListOperations ● Empty list ○ [] or list() ● Non-empty list ○ l1 = [“Mary”, “had”, “a”, “little”, “lamb”]; l2 = [1, 2, 3.14]; l3 = [[1,2,3.14], [“Mary”, “had”]] ● List indexing ○ l1[0] → “Mary”; l2[-1] = 3; l2[2] → 3; l3[0][0] → “Mary”; l3[-1][-1][-1] → “d” ● List alternation ○ l1.append(item) → None; l1.extend(list) → None; l1.sort() → None; l1.remove(item) → None 3
  • 4.
    ● Empty tuple ○(,) or tuple() ● Non-empty tuple ○ t1 = (“Mary”, “had”, “a”, “little”, “lamb”); t2 = (1, 2, 3.14); t3 = ([1,2,3.14], [“Mary”, “had”]) ● Tuple indexing ○ t1[0] → “Mary”; t2[-1] = 3; t2[2] → 3.14; t3[0][0] → “Mary”; t3[-1][-1][-1] → “d” ● Other tuple operations ○ t1.count(item) → int; t1.index(item) → item Tuples and Tuple Operations 4 IMMUTABLE!
  • 5.
    Dictionaries and DictionaryOperations ● Empty dictionary ○ {} or dict() ● Non-empty dictionary ○ d = {“Mary” : 1, “had” : 2, “a” : 3, “little” : 4, “lamb” : 5}; d = dict([(“Mary”, 1), (“had”, 2), (“a”, 3)]) ● Dictionary indexing ○ d[“Mary”] → 1; d[“lamb”] = None; d[“lamb”] → None ● Dictionary alternation ○ d.update({key:value}) → None; d[newkey]=newvalue; del d[key] 5 All keys must be different and immutable.
  • 6.
    Sets and SetOperations ● Empty set ○ set() ● Non-empty set ○ s = set([“Mary”, “had”, “a”, “little”, “lamb”]) ● Set alternation ○ s.add(item) → set; s.remove(item) → set; s.clear() → set ● Set theoretic operations ○ s1 | s2 → union of sets; s1 & s2 → intersection of sets; s1 - s2 → difference of sets 6 Cannot be indexed. All elements unique.
  • 7.
    Generator Functions (“lazy”functions) ● Produce one item at a time; more efficient that lists ● Most common generators: ○ range(x=0,y,z=1) → numbers from y (inclusive) to x (not inclusive) with step z ○ enumerate(l) → tuples (0, l[0]), (1, l[1]), (2, l[2]), … ○ zip(l1, l2) → tuples (l1[0], l2[0]), (l1[1], l2[1]), (l2[1], l2[2]), … ● Lists and dictionaries from generators: ○ list(range(n)); list(enumerate(items)); list(zip(first_items, second_items)) ○ dict(enumerate(values)); dict(zip(keys, values)) 7
  • 8.
    List Comprehensions ● Aconcise and powerful way of running a “foreach” loop ○ result = [action(item) for item in collection if condition(item)] Apply action() to each item in the collection (string, list, set, tuple, dictionary), for which the condition is True, and collect the results into a list. The condition is optional (default: True). ● Examples: ○ [c.upper() for c in “Hello, world!”] → list of upper-cased characters ○ “”.join([c for c in “Mary had a little lamb”] if c not in “aouie”]) → string with removed vowels ○ [x**2 for x in range(10) if x % 3 == 0] → list of squares if divisible by 3 ○ [key[0] for key in some_dict] → list of first characters of all keys 8
  • 9.
    Cool Idioms ● Removeduplicates from list l ○ list(set(l)) ● Remove multiple spaces from string s ○ “ ”.join(s.split()) ● Swap keys and values in dictionary d (duplicate value will be removed) ○ dict([(v,k) for (k,v) in d.items()]) ● Nested list comprehension: read all lines from file and remove all leading and trailing white spaces and empty lines 9
  • 10.
    Counters ● Creation ○ fromcollections import Counter ○ cntr = Counter(any_collection) → Counter object ● Use ○ freqs.most_common(n=all) → list of tuples (item, frequency), ordered by decreasing frequency ○ cntr = Counter(‘mary had a little lamb’) ○ cntr.most_common(5) → [(' ', 4), ('a', 4), ('l', 3), ('m', 2), ('t', 2)] ● Frequency dictionary 10
  • 11.
    Files ● Opening ○ infile= open(name, “r”); outfile = open(name, “w”); outfile_with_append = open(name, “a”) ○ bin_infile = open(name, “rb”); bin_outfile = open(name, “wb”) ● Closing ○ infile.close(); outfile.close() ○ with open(name, mode) as file_handle: do_something(file_handle) # No need to close the file! ● Reading: ○ infile.read(n=all) → string of at most n characters; bin_infile(n=all) → at most n bytes 11
  • 12.
    URLs and Exceptions importurllib.request, sys url = “http://networksciencelab.com” try: page = urllib.request.urlopen(url) html = page.read() # 😊 except: print() # 😞 sys.exit(1) 12