SlideShare a Scribd company logo
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

More Related Content

PPTX
Master's Thesis
PPTX
Hash table and heaps
PDF
Algebra 2 Unit 5 Lesson 2
PDF
Data Structures In Scala
PDF
Why Haskell Matters
PPTX
5 4 function notation
PPTX
C# 6.0
PDF
Day 5 examples
Master's Thesis
Hash table and heaps
Algebra 2 Unit 5 Lesson 2
Data Structures In Scala
Why Haskell Matters
5 4 function notation
C# 6.0
Day 5 examples

What's hot (19)

PPTX
Functional Programming, simplified
PDF
Polynomial functions
DOC
BingoConsoleApp
PDF
The Ring programming language version 1.6 book - Part 35 of 189
KEY
ぐだ生 Java入門第一回(equals hash code_tostring)
PPTX
Lecture 4 data structures and algorithms
PPTX
Yin Yangs of Software Development
PDF
Numpy Meetup 07/02/2013
PPTX
Print input-presentation
PDF
The Ring programming language version 1.9 book - Part 41 of 210
DOC
Simultaneous eqn2
PDF
High-Performance Haskell
PDF
Ch16 11
PDF
Scheme 核心概念(一)
PDF
The Ring programming language version 1.9 book - Part 38 of 210
PPT
02-04 Relations Functions
PDF
The Ring programming language version 1.6 book - Part 32 of 189
PDF
ECMAScript 6 major changes
Functional Programming, simplified
Polynomial functions
BingoConsoleApp
The Ring programming language version 1.6 book - Part 35 of 189
ぐだ生 Java入門第一回(equals hash code_tostring)
Lecture 4 data structures and algorithms
Yin Yangs of Software Development
Numpy Meetup 07/02/2013
Print input-presentation
The Ring programming language version 1.9 book - Part 41 of 210
Simultaneous eqn2
High-Performance Haskell
Ch16 11
Scheme 核心概念(一)
The Ring programming language version 1.9 book - Part 38 of 210
02-04 Relations Functions
The Ring programming language version 1.6 book - Part 32 of 189
ECMAScript 6 major changes
Ad

Similar to Python overview (20)

PPTX
Datastructures in python
PPT
Introduction to Python Programming.ppt
PDF
Processing data with Python, using standard library modules you (probably) ne...
PPT
Python tutorial
PDF
python.pdf
PPTX
Python introduction data structures lists etc
PDF
Python: The Dynamic!
PPTX
Python material
PPTX
Python Workshop
PPTX
Python Lecture 11
PPTX
cover every basics of python with this..
PPT
ComandosDePython_ComponentesBasicosImpl.ppt
PDF
Anton Kasyanov, Introduction to Python, Lecture4
PDF
جلسه سوم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
PPT
Python programming tutorial for beginners
PPT
Tuples, sets and dictionaries-Programming in Python
PPTX
GE8151 Problem Solving and Python Programming
PDF
Python Workshop Part 2. LUG Maniapl
PPTX
Learn python - for beginners - part-2
PDF
A tour of Python
Datastructures in python
Introduction to Python Programming.ppt
Processing data with Python, using standard library modules you (probably) ne...
Python tutorial
python.pdf
Python introduction data structures lists etc
Python: The Dynamic!
Python material
Python Workshop
Python Lecture 11
cover every basics of python with this..
ComandosDePython_ComponentesBasicosImpl.ppt
Anton Kasyanov, Introduction to Python, Lecture4
جلسه سوم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
Python programming tutorial for beginners
Tuples, sets and dictionaries-Programming in Python
GE8151 Problem Solving and Python Programming
Python Workshop Part 2. LUG Maniapl
Learn python - for beginners - part-2
A tour of Python
Ad

More from Dmitry Zinoviev (20)

PDF
What You Can Learn from Obscure Programming Languages
PDF
Machine Learning Basics for Dummies (no math!)
PDF
WHat is star discourse in post-Soviet film journals?
PDF
The “Musk” Effect at Twitter
PDF
Are Twitter Networks of Regional Entrepreneurs Gendered?
PDF
Using Complex Network Analysis for Periodization
PDF
Algorithms
PDF
Text analysis of The Book Club Play
ODP
Exploring the History of Mental Stigma
ODP
Roles and Words in a massive NSSI-Related Interaction Network
PDF
“A Quaint and Curious Volume of Forgotten Lore,” or an Exercise in Digital Hu...
PDF
Network analysis of the 2016 USA presidential campaign tweets
PDF
Network Analysis of The Shining
PDF
The Lord of the Ring. A Network Analysis
PPTX
Pickling and CSV
PPTX
Welcome to CS310!
ODP
Programming languages
ODP
The P4 of Networkacy
PDF
DaVinci Code. Network Analysis
PDF
Soviet Popular Music Landscape: Community Structure and Success Predictors
What You Can Learn from Obscure Programming Languages
Machine Learning Basics for Dummies (no math!)
WHat is star discourse in post-Soviet film journals?
The “Musk” Effect at Twitter
Are Twitter Networks of Regional Entrepreneurs Gendered?
Using Complex Network Analysis for Periodization
Algorithms
Text analysis of The Book Club Play
Exploring the History of Mental Stigma
Roles and Words in a massive NSSI-Related Interaction Network
“A Quaint and Curious Volume of Forgotten Lore,” or an Exercise in Digital Hu...
Network analysis of the 2016 USA presidential campaign tweets
Network Analysis of The Shining
The Lord of the Ring. A Network Analysis
Pickling and CSV
Welcome to CS310!
Programming languages
The P4 of Networkacy
DaVinci Code. Network Analysis
Soviet Popular Music Landscape: Community Structure and Success Predictors

Recently uploaded (20)

PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
DOCX
The AUB Centre for AI in Media Proposal.docx
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PPTX
Big Data Technologies - Introduction.pptx
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PDF
Network Security Unit 5.pdf for BCA BBA.
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
PDF
cuic standard and advanced reporting.pdf
PDF
Approach and Philosophy of On baking technology
PDF
Unlocking AI with Model Context Protocol (MCP)
PDF
Encapsulation theory and applications.pdf
Digital-Transformation-Roadmap-for-Companies.pptx
The AUB Centre for AI in Media Proposal.docx
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Big Data Technologies - Introduction.pptx
Advanced methodologies resolving dimensionality complications for autism neur...
20250228 LYD VKU AI Blended-Learning.pptx
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
Building Integrated photovoltaic BIPV_UPV.pdf
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
NewMind AI Weekly Chronicles - August'25 Week I
Network Security Unit 5.pdf for BCA BBA.
Per capita expenditure prediction using model stacking based on satellite ima...
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
cuic standard and advanced reporting.pdf
Approach and Philosophy of On baking technology
Unlocking AI with Model Context Protocol (MCP)
Encapsulation theory and applications.pdf

Python overview

  • 1. Essential Python Overview of the 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 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
  • 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 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.
  • 6. 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.
  • 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 ● 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
  • 9. 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
  • 10. 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
  • 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 import urllib.request, sys url = “http://networksciencelab.com” try: page = urllib.request.urlopen(url) html = page.read() # 😊 except: print() # 😞 sys.exit(1) 12