Return to site

Python Cheat Sheet 2019

broken image


By Stef Maruch, Aahz Maruch. New to programming in Python? Whether you're working with string methods or built-in functions in Python, this Cheat Sheet helps you program the correct order for the operation so you achieve the correct result. Not only this, Python being a high-level language it has plenty of libraries to that make your work easier, libraries for data analysis, computer vision, web development and more. Download Python 3 Beginners Cheat Sheet. Join Python Programming Bootcamp. Dependencies and Setup¶. In the Python code we assume that you have already run import numpy as np. In the Julia, we assume you are using v1.0.2 or later with Compat v1.3.0 or later and have run using LinearAlgebra, Statistics, Compat.

Python Cheat Sheet 2019

Python Cheat Sheet 3

  • MATLAB–Python–Julia cheatsheet

Dependencies and Setup¶

In the Python code we assume that you have already run importnumpyasnp

Cheat

Python Cheat Sheet 3

  • MATLAB–Python–Julia cheatsheet

Dependencies and Setup¶

In the Python code we assume that you have already run importnumpyasnp

In the Julia, we assume you are using v1.0.2 or later with Compat v1.3.0 or later and have run usingLinearAlgebra,Statistics,Compat

Creating Vectors¶

Operation

MATLAB

Python

Julia

Row vector: size (1, n)

Column vector: size (n, 1)

1d array: size (n, )

Not possible

or

Integers from j to n withstep size k

Linearly spaced vectorof k points

Creating Matrices¶

Operation

MATLAB

Python

Julia

Create a matrix

2 x 2 matrix of zeros

2 x 2 matrix of ones

2 x 2 identity matrix

Diagonal matrix

Uniform random numbers

Normal random numbers

Sparse Matrices

Tridiagonal Matrices

Manipulating Vectors and Matrices¶

Operation

MATLAB

Python

Julia

Transpose

Complex conjugate transpose(Adjoint)

Concatenate horizontally

or

or

Concatenate vertically

or

or

Reshape (to 5 rows, 2 columns)

Convert matrix to vector

Flip left/right

Flip up/down

Repeat matrix (3 times in therow dimension, 4 times in thecolumn dimension)

Preallocating/Similar

N/A similar type

Broadcast a function over acollection/matrix/vector

Functions broadcast directly

Functions broadcast directly

Accessing Vector/Matrix Elements¶

Operation

MATLAB

Python

Julia

Access one element

Access specific rows

Access specific columns

Remove a row

Diagonals of matrix

Get dimensions of matrix

Mathematical Operations¶

Operation

MATLAB

Python

Julia

Dot product

Matrix multiplication

Final cut pro 10 4 1. Inplace matrix multiplication

Not possible

Element-wise multiplication

Matrix to a power

Matrix to a power, elementwise

Inverse

or

or

Determinant

Eigenvalues and eigenvectors

Euclidean norm

Solve linear system(Ax=b) (when (A)is square)

Solve least squares problem(Ax=b) (when (A)is rectangular)

Sum / max / min¶

Operation

MATLAB

Python

Julia

Sum / max / min ofeach column

Sum / max / min of each row

Sum / max / min ofentire matrix

Cumulative sum / max / minby row

Cumulative sum / max / minby column

Programming¶

Operation

MATLAB

Python

Julia

Comment one line

Comment block

For loop

While loop

If

If / else

Print text and variable

Function: anonymous

Function

Tuples

Can use cells but watch performance

Named Tuples/Anonymous Structures

Closures

Inplace Modification

No consistent or simple syntaxto achieve this

New to programming in Python? No worries. Whether you're working with string methods or built-in functions in Python, this Cheat Sheet helps you program the correct order for the operation so you achieve the correct result.

Python String Methods

The following list shows you how to perform common string methods, or actions on a string, in Python. Type the specific order to achieve the desired result.

SyntaxAction
S.count(substring[, start[, end]])Count occurrences of substring
S.decode([encoding])Decode to Unicode using default encoding
S.encode([encoding])Encode from Unicode using default encoding
S.endswith(suffix[, start[, end]])True if S ends with suffix
S.find(substring [,start [,end]])Find first occurrence of substring and return its index
number; if not found, return -1
S.index(substring [,start [,end]])Find first occurrence of substring and return its index
number; if not found, raise ValueError
S.isalnum()True if S has only alphanumeric characters
S.isalpha()True if S has only alphabetic characters
S.isdigit()True if S has only digits
S.isspace()True if S has only whitespace characters
S.join(iterable)Using S as a separator, stick together the strings in
iterable
S.lower()Convert S to lowercase
S.lstrip([chars])Remove whitespace (or chars) from front (left) of
S
S.replace (old, new[, count])Replace old (a substring) with new
S.rfind(substring [,start [,end]])Find the last (rightmost) occurrence of substring and
return its index number; if not found, return -1
S.rindex(substring [,start [,end]])Find the last (rightmost) occurrence of substring and
returns its index number; if not found, raise ValueError
S.rstrip([chars])Remove whitespace (or chars) from end (right) of
S
S.split([separator [,maxsplit]])Split S using whitespace (or separator) and
return a list of substrings
S.startswith(prefix[, start[, end]])True if S starts with prefix
S.strip([chars])Remove characters at beginning and end of S; default is
whitespace characters
S.upper()Convert S to uppercase
Note: String methods that change a string always
return a copy; the original string remains unchanged.

Python's Built-In Functions

Built into the Python interpreter are a number of functions (pieces of code that carry out specific operations and return the results of those operations), including math functions other than the standard arithmetic operators. Here's a list of Python's built-in functions along with their pattern and corresponding action:

SyntaxAction
abs(number)Return absolute value of number
all(iterable)Return True unless at least one element is false
any(iterable)Return False unless at least one element is true
chr(integer)Return the character with the specified ASCII value (must be
between 0 and 256)
delattr(object, name), del x.yDelete the named attribute from object
dir([object])Return the names in the current namespace or object‘s
namespace
eval(source[, globals[, locals]])Execute source as a Python expression
getattr(object, name[, default]) x.yReturn specified attribute (name) of object,
raising AttributeError if not found; optional: return
default if name doesn't exist
globals()Return dict of global names in the current namespace
hasattr(object, name)True if object has the specified attribute
(name)
isinstance(object, class-or-type)True if object is an instance of the specified class (or
its subclasses) or type; optional: specify multiple classes or
types using a tuple
issubclass(C, B)True if class C is a subclass of class B;
optional: specify multiple classes using a tuple
iter(iterable)Return an iterator over iterable
len(object)Return number of items in a sequence or dict
locals()Return dictionary of local names in the current namespace
max(iterable), max(a, b, c, …)Return largest item of iterable or argument list
min(iterable), min(a, b, c, …)Return smallest item of iterable or argument list
ord(char)Return the ASCII value of a one-character string
range([start,] stop[, step])Return a list of integers from 0 up to (but not
including) stop

Python Cheat Sheet Pdf

raw_input([prompt])Return a string from standard input (usually something the user
types), not including the newline character
repr(object)Return canonical string representation of object
round(number[, ndigits])Return floating-point number rounded to nearest integer
setattr(object, name, value) x.y = vSet object‘s attribute to the specified value
sorted(iterable[, cmp [, key [, reverse])Return a new sorted list; optional: cmp and key
take functions as arguments; reverse=True
sum(iterable[, start=0])Return the sum of all elements of iterable; does not
work with strings
unichr(integer)Return a Unicode string corresponding to integer, which
must be between 0 and 0x10ffff
xrange([start,] stop[, step])Return an iterable that generates a range from 0 up to
(but not including) stop
zip([iter1 [, iter2 [, …]]])Take zero or more iterables and return a list of tuples that
group the items at a particular index number; the list returned is
the same length as the shortest iterable




broken image