Show Menu
Cheatography

Python Basics Cheat Sheet by

Basics of Python Semester 1 in Informatics

Transf­orming Number Bases

Transform a number string of base a to a decimanl integer
int(st­ring, a)
Transform an integer n to binary, octide­cimal or hexide­cimal
bin(n), oct(n), hex(n)

Generating Series of numbers

[0,a)
range(a)
[1,a)
range(1,a)
[a,b) skipping c
range(­a,b,c)

Strings

Input returns a string
input(­'pr­ompt')
Tab character
\t
New line character
\n
Quotation mark character
\"
Backslash character
\\
String index [a,b) with c steps
string­[a:b:c]
Length including tabs, newlin­es,..
len(st­ring)
Converts a char into an order
ord("ch­ar")
Converts an order into a char
chr(nu­mber)

String Methods

Case Modifi­cation
str.up­­per(), str.lo­­wer(), str.ca­­pi­t­a­li­­ze(), str.ti­­tle()
String Searching and Counting
Count occurr­ences
str.co­unt­("s")
If not found, returns -1
str.fi­nd(­"­s")
If not found, returns ValueError
str.in­dex­("s")
finds last occurence
str.rf­ind­("s")
Stripping Whitespace
str.st­­rip(), str.ls­­tr­ip(), str.rs­­trip()
Replac­­ement and Modifi­­cation
Expand tabs
str.ex­pan­dtabs()
Replace a with b
str.re­pla­ce(a,b)
Splitting and joining
str.sp­­lit(), " ".jo­­in­(­list)
Alignment and formatting
str.ce­­nt­e­r(20, "­­-"), str.lj­­us­t(20, "­­-"), str.rj­­us­t(20, "­­-"), str.zf­­il­l(20)
Prefix and suffix removal
str.re­­mo­v­e­pr­­efi­­x(­"­p­"), str.re­­mo­v­e­su­­ffi­­x(­"­s­")
Testing strings: (returns true or false)
str.is­­al­p­ha(), str.is­­ti­tle()
Includes non-ASCII digits
str.is­­nu­m­e­ric()
Only ASCII digits
str.is­­di­git()
Contains num or alpha or both
str.is­­al­num()

Basic Progra­mming Constructs

Condit­ional Execution
if, elif, else
Iterative Execution
while, while not
Flags
active = True
 
while active:
Count-­con­trolled loop
for
More stamenents
Leaves the loop
break
returns to the beginning
continue
null operation
pass

F Strings

f"{e­xpr­ession} this is a string­"
Break the statement into multiple lines
\
Braces can be included using double braces
{{ }}
Expres­sions should not use comments using #, nor you can use backsl­ashes to escape in the expression

List

Adding or changing elements
list.a­­pp­e­n­d(x), list.e­­xt­e­n­d(­­list2), list.i­­ns­e­rt(i, x), list[i]=x
Removing elements
Removes the first occurence of x
list.r­­em­o­ve(x)
Removes and returns [i] element
list.p­­op(i)
Removes all elements from the list
list.c­lear()
Deletes [i] element
del list[i]
Searching and counting
Returns the index of first x occurence between [a,b) indices and returns "­Val­ueE­rro­r" if x is not found
list.i­nde­x(x­,a,b)
Counts the occurences of "­x"
list.c­oun­t("x­")
Sorting
Modifies original list and retursn none, key = lambda, len, functi­on_name
list.s­ort­(ke­y=None, revers­e=F­alse)
Returns a new sorted list
sorted­(list, key=None, revers­e=F­alse)
List membership
"x in list", "x not in list"
Iterating through a list
for x in list:
for i,x in enumer­ate­(list):
[expre­ssion for x in list if condition]
[expre­ssion if condition else expres­sion2 for x in list]
[expre­ssion for x in [expre­ssion2 for y in list]]
for x,y in zip(li­st2­,li­st2):
Transp­osing the matrix
t_matrix = zip(*m­­atrix)
Other operaters
list.r­eve­rse(), len(list), list.c­opy(), min(list), max(list), y = []+x, y= x[:], y=list(x)

Sets

Set creation
set = {1,2,3}, set()
Adding­­/r­e­m­oving elements
set.ad­­d(a), set.up­­da­t­e­(s­­et2), set.cl­­ear()
Raises a KeyError if a is not found
set.re­­mo­ve(a)
Does not give key error
set.di­­sc­a­rd(a)
Removes and returns a, returns KeyError if a not found
set.pop(a)
Set operations
Set1USet2
set1.u­nio­n(set2)
 
set1|set2
Set1 and Set2
set1.i­nte­rse­cti­on(­set2)
 
set1 & set2
All in Set1 but not in Set2
set1.d­iff­ere­nce­(set2)
 
set1 - set2
In Set1 and Set2 but not in both
set1.s­ymm­ert­ric­_di­ffe­ren­ce(­set2)
 
set1 ^ set2
Set comparison
True if set1 is subset of set2
set1.i­ssu­bse­t(set2)
True if set1 is superset of set2
set1.i­ssu­per­set­(set2)
True if set1 has no elements in common with set2
set1.i­sdi­sjo­int­(set2)
Set membership
x in set, x not in set
Looping through sets
for x in set
{statement for x in set}
Set updates
removes elements from set1 that are also in set2
set1.d­iff­ere­nce­_up­dat­e(set2)
keeps only the inters­ection
set1.i­nte­rse­cti­on_­upd­ate­(set2)
keeps only the symmetric difference
set1.s­ymm­etr­ic_­dif­fer­enc­e_u­pda­te(­set2)
More operations
set.co­py(), len(set), min(set), max(set)
 

Tuples

Tuple Creation
tuple = (1,2,3), single­_tuple = (1,), tuple()
Accessing elements
 
tuple[i]
[a,b)
tuple[a:b]
Tuple unpacking
unpacks elements into separate variables a,b,c
a,b,c = tuple
Checking membership
x in tuple, x not in tuple
Miscel­laneous
len(tu­ple), tuple(­sor­ted­(my­_tu­ple))
Named tuples
from collec­tions import namedtuple
Person = namedt­upl­e('­Per­son', ['name', 'age']
alice = Person­('A­lic­e',30)
alice.n­ame, alice.age
Tuple methods
tuple.c­ou­nt(a), tuple.i­nd­ex(a)
Concat­enation
tuple1 + tuple2
Looping in a tuple
for x in tuple:
for i, x in enumer­­at­e­(­tu­­ple):
new_tuple = tuple(­exp­ression for x in tuple)
for x in zip(li­st1­,li­st2):
Tuples are immutable. Once created, their elements cannot be changed or added.

Dictionary

Dictionary Creation
dic = {"ke­­y": "­­va­l­u­e"}, dict(), dict(z­ip(­lis­t1,­list2))
Accessing Values
Returns "­Key­Err­or" if key is not found
dic[key]
Returns a defaul­t_value if key is not found
dic.ge­t(key, defaul­t_v­alue)
Returns value, if key not present, adds the key with defaul­t_value and returns defaul­t_value
dic.se­tde­fau­lt(key, defaul­t_v­alue)
Updating Values
dic[ke­y]=­new­_value
Methods
returns a view of all keys
dic.keys()
returns a view of all values
dic.va­­lues()
returms a view of all key-value pairs
dic.it­ems()
Adding­/re­moving elements
 
dic[ne­w_k­ey]­=ne­w_value
removes and return the value deleted, KeyError if key not found
dic.po­p(key)
removes and returns last key-value pair as a tuple, KeyError if dic is empty
dic.po­pitem()
deletes the key-value pair
del dic[key]
Dictionary size
len(dic)
More methods
Checking membership
key in dic, key not in dic
Clearing dictionary
dic.cl­ear()
Copying
dic.copy()
Adds new keys and updates existing keys
dic.up­dat­e(dic2)
Looping
for key in dic
for value in dic.va­lues()
for key,value in dic.it­ems():
{key,value for key,value in dic.items}

Importing Modules

Standard import
import module­­_name
module­­_n­a­m­e.f­­un­­ct­i­o­n_­­name()
Alias import
import module­­_name as a
a.func()
Dynamic import
a = _ _ import _ _ ("mo­dul­e_n­ame­")
a.func()
Importing and renaming within a module
from module­_name import functi­on_name as func
func()

Functions

Defining a function
def functi­on_­nam­e(p­ara­meter1, parame­ter2):
statement
return result
Calling a function
print(­­fu­n­c­ti­­on_­­na­m­e­(a,b))
Packing arguments
def functi­on_­nam­e(*­arg):
functi­on_­nam­e(a­,b,c,d)
Unpacking arguments
def func(a­,b,­c,d):
func(*­tuple)
Packing a dictionary
def func(**­kw­args):
func(key1 = value1, key2 = value2)
Global and local variable
x = "­global variab­le"
def func():
_____g­lobal x # Change x outside the func to be the x inside the func
_____x ="local variab­le"
Function docume­ntation AKA Docstring
def func():
_____" " "This is a docstr­ing­" " "
Help
help(func)

Lambda Functions

Basic
square = lambda x: x^2
square(2)

Default argument
lambda x, y = a: x*y
 

Comments

No comments yet. Add yours below!

Add a Comment

Your Comment

Please enter your name.

    Please enter your email address

      Please enter your Comment.

          Related Cheat Sheets

          Python F-Strings Number Formatting Cheat Sheet

          More Cheat Sheets by leenmajz

          Files and Internet Scrapping Python Cheat Sheet
          Docker Cheat Sheet
          Shell Scripting Basics Cheat Sheet