Scripting >> Python >> Cheatsheet >> Python 3 cheatsheet

Jump to: Boolean Constants | Classes | Comments | Data Types | Debugging | Dictionary | Exceptions | For | File I/O | Format Specifier | Functions If  | Lists | Lambda | Operators | Operator Precedence | Output Format | Sets | Strings | Try | Tuples | While | continue to Modules | official tutorials | official language reference 

 

Reserved words
and class elif finally if lambda or True yield
as continue else for import None pass try  
assert def except from in nonlocal raise while  
break del False global is not return with  

 

Built in functions

Operators
Operator Description Operator methods
(import operator)
or
and
not
Boolean OR, AND, NOT operator.and_(a,b)
in
not in
Membership.  Returns True if is a member and False if is not operator.in(a,b)
is
is not
Identity operator.is_(a,b)
operator.is_not(a,b)
<
<=
>
>=
!=
==
Relational operator.lt(a,b)
operator.le(a,b)
operator.gt(a,b)
operator.ge(a,b)
operator.ne(a,b)
 

|

Bitwise OR operator.or_(a,b)
^ Bitwise XOR operator.xor(a,b)
& Bitwise AND operator.and_(a,b)
~ Bitwise NOT operator.inv(a)
<<
>>
Bitwise shift left
Bitwise shift right
operator.lshift(a,b)
operator.right(a,b)

+=
&=
-=
|=
*=
^=
/=
>>=
<<=
%=
**=
//=

Compound assignment operator.iadd(a,b)
operator.iand(a,b)
operator.isub(a,b)
operator.ior(a,b)
operator.imul(a,b)
operator.ixor(a,b)
operator.itruediv(a,b)
operator.irshift(a,b)
operator.ilshift(a,b)
operator.imod(a,b)
operator.ipower(a,b)
operator.ifloordiv(a,b)
+
-
*
/
//
%
**
add
subtract
multiply
divide
floor divide
modulus (remainder)
exponentiation
operator.add(a,b)
operator.sub(a,b)
operator.mul(a,b)
operator.truediv(a,b)
operator.floordiv(a,b)
operator.mod(a,b)
operator.pow(a,b)
@ matrix multiplication operator.matmul(a,b)

 Go Top

Debugging

import pdb
pdb.set_trace()

Sets break point at following line.

n : Execute next line
c : complete execution
l : list lines before and after the current line
s : step into function call
b : show list of all breakpoints
cl : clear all break points

assert
:: Assert statements are a convenient way to insert debugging assertions into a program, tests the condition and continue if true and halt the program if false.

Example

>>> def average(numbers):
...    assert len(numbers) !=0,"Error Description"
...    return sum(numbers)/len(numbers)
...
>>> N1=[1,2,3]
>>> print(average(N1))
2
>>> N2=[]
>>> print(average(N2))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in average
AssertionError: Error Description

 

 Go Top

Standard Exceptions
OverflowError Calculation exceeds maximum limit for a numeric type
ZeroDivisionError Division by zero
IOError Input or output function fails
IndexError An index is not found in a sequence
KeyError a specified key is not found in the dictionary
UnboundLocalError Trying to access a local variable that has no value
RuntimeError Generated when error does not fall into any category
Type Error Operation applied on object of wrong type
ValueError

Invalid value for a data type

 

Boolean Constants
Boolean true True
Boolean false False

  

Comments
# for single line coment """
For
Multiline
Comments
"""

 

 Go Top

 

 
Operator precedence
x[i], x[i:j], x(args), x.attr Subscription, slicing, call,
attribute reference
 
()
parentheses  
** exponentiation expressions evaluated from right to left i.e. right side first
+x, -x, ~x Positive, negative, bitwise NOT  
* , @,/ , // , % multiply, matrix multiply,
divide, floor divide,
modulus

These have same precedence, but expressions evaluated from left to right
 

+  - add, subtract left to right
<< , >> Shifts  
& Bitwise AND  
^ Bitwise XOR  
| Bitwise OR  
in, not in,
is, is not
<,<=,>,>=,!=,==
Membership tests,
Identity tests,
relational operators
 
not Boolean NOT  
and Boolean AND  
or Boolean OR  

Go Top

If .. elif .. else
if condition1 :
␣␣␣␣# condition1 true code
[elif condition2:
␣␣␣␣# condition2 true code ]
[else :
␣␣␣␣# else code ]

 Go Top

Try ... except ... else ... finally
try:
␣␣␣␣# code with possible runtime error
except [type [as value]]:
␣␣␣␣# code when there is error
[else:
␣␣␣␣# code when there is NO error ]
␣␣␣␣# or just 'pass' statement if nothing to execute
[finally:
␣␣␣␣# code to run always  ]

Example 1 - read 2 values perform int division

>>> a,b = input().split()
1 0
>>> try:
...     print(int(a) // int(b))
... except ValueError as error:
...     print("Error code:",error)
... except ZeroDivisionError as error:
...     print("Error code:",error)
...
Error code: integer division or modulo by zero

>>> a,b = input().split()
2 $
...
Error code: invalid literal for int() with base 10: '$'

 

 Go Top

For ... loop
for identifier in list :
␣␣␣␣# list processing code
␣␣␣␣[if somecondition1
␣␣␣␣␣␣␣␣break # exit the loop now]
␣␣␣␣[if somecondition2
␣␣␣␣␣␣␣␣continue # jump to next cycle in the loop]
␣␣␣␣# more processing code
[else :
␣␣␣␣# code to run when loop ends
␣␣␣␣# without a break 
␣␣␣␣]

 Go Top

While ... loop

while condition
␣␣␣␣# repeat code if condition is true
␣␣␣␣[if somecondition1
␣␣␣␣␣␣␣␣break # exit the loop now]
␣␣␣␣[if somecondition2
␣␣␣␣␣␣␣␣continue # jump to next cycle in the loop]
␣␣␣␣# more processing code
[else:
␣␣␣␣# code when condition is false
␣␣␣␣# and terminate ]

 

Data Types

Text Type:

str
Numeric Types: int, float, complex
Sequence Types: list, tuple, range
Mapping Type: dict
Set Types: set, frozenset
Boolean Type: bool
Binary Types: bytes, bytearray, memoryview

Go Top

     

 

Functions
Built-in Functions
Function Syntax
Description
abs() abs(x) Return the absolute value of the argument
all() all(iterable) Return True if bool(x) is True for all values x in the iterable. If the iterable is empty, return True
any() any(iterable) Return True if bool(x) is True for any x in the iterable. If the iterable is empty, return False.
ascii() ascii(obj) Return an ASCII-only representation of an object.  As repr(), return a string containing a printable representation of an object, but escape the non-ASCII characters in the string returned by  repr() using \x, \u or \U escapes. This generates a string similar to that returned by repr() in Python 2.
bin() bin(number) Return the binary representation of an integer
bool() bool(int) Returns True when the argument x is true, False otherwise.
breakpoint() breakpoint(*args, **kws) Call sys.breakpointhook(*args, **kws).  sys.breakpointhook() must accept whatever arguments are passed. By default, this drops you into the pdb debugger.
bytearray() bytearray(iterable_of_ints)
bytearray(string, encoding[, errors])
bytearray(bytes_or_buffer)
bytearray(int)
bytearray()
Construct a mutable bytearray object from:
- an iterable yielding integers in range(256)
- a text string encoded using the specified encoding
- a bytes or a buffer object
- any object implementing the buffer API.
- an integer
bytes() bytes(iterable_of_ints)
bytes(string, encoding[, errors])
bytes(bytes_or_buffer)
bytes(int)
bytes()

Construct an immutable array of bytes from:
- an iterable yielding integers in range(256)
- a text string encoded using the specified encoding
- any object implementing the buffer API.
- an integer

Go Top

callable() callable(obj) Return whether the object is callable (i.e., some kind of function)
chr() chr(i) Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff
classmethod() classmethod(function) Convert a function to be a class method
compile() compile(source, filename, mode, flags=0, dont_inherit=False, optimize=-1) The source code may represent a Python module, statement or expression. The filename will be used for run-time error messages. The mode must be 'exec' to compile a module, 'single' to compile a single (interactive) statement, or 'eval' to compile an expression. The flags argument, if present, controls which future statements influence the compilation of the code. The dont_inherit argument, if true, stops the compilation inheriting the effects of any future statements in effect in the code calling compile; if absent or false these statements do influence the compilation, in addition to any features explicitly specified
complex() complex(real=0, imag=0) Create a complex number from a real part and an optional imaginary part
delattr() delattr(obj, name) Deletes the named attribute from the given object.  delattr(x, 'y') is equivalent to ``del x.y''
dict() dict()
dict(mapping)
dict(iterable)
dict(**kwargs)
Create new empty dictionary.
Create new dictionary initialized from a mapping object's (key, value) pairs
Create new dictionary initialized by for k,v in iterable d[k] = v
Create new dictionary initialized with the name=value pairs in the keyword argument list. 
dir() dir([object]) If called without an argument, return the names in the current scope.
    Else, return an alphabetized list of names comprising (some of) the attributes
    of the given object, and of attributes reachable from it
divmod() divmod(x, y) Return the tuple (x//y, x%y).
enumerate() enumerate(iterable, start=0)

The enumerate object yields pairs containing a count (from start, which
 |  defaults to zero) and a value yielded by the iterable argument.

>>> L=[2,4,6,8]
>>> for c in enumerate(L,2):
...    print(c)
...
(2, 2)
(3, 4)
(4, 6)
(5, 8)
>>> for c in enumerate(L):
...    print(c)
...
(0, 2)
(1, 4)
(2, 6)
(3, 8)

Go Top

eval() eval(source, globals=None, locals=None)

Evaluate the given source in the context of globals and locals.

The source may be a string representing a Python expression or a code object as returned by compile(). The globals must be a dictionary and locals can be any mapping, defaulting to the current globals and locals. If only globals is given, locals defaults to it

example

>>> x = 1 >>> eval('x+1') 2
exec() exec(source, globals=None, locals=None) Execute the given source in the context of globals and locals.

The source may be a string representing a Python expression or a code object as returned by compile(). The globals must be a dictionary and locals can be any mapping, defaulting to the current globals and locals. If only globals is given, locals defaults to it
filter() filter(function or None) Return an iterator yielding those items of iterable for which function(item) is true. If function is None, return the items that are true
float() float(x=0 Convert a string or number to a floating point number
format() format(value, format_spec='' Return value.__format__(format_spec)
frozenset() frozenset()
frozenset(iterable)
Build an immutable unordered collection of unique elements
getattr() getattr(object, name[, default]) Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y. When a default argument is given, it is returned when the attribute doesn't exist; without it, an exception is raised in that case
globals() globals() Return the dictionary containing the current scope's global variables
hasattr() hasattr(obj, name) Return whether the object has an attribute with the given name
hash() hash(obj) Return the hash value for the given object.
Two objects that compare equal must also have the same hash value, but the reverse is not necessarily true
hex() hex(number) Return the hexadecimal representation of an integer
id() id(obj Return the identity of an object. This is guaranteed to be unique among simultaneously existing objects
input() input(prompt=None) Read a string from standard input.  The trailing newline is stripped.
The prompt string, if given, is printed to standard output without a trailing newline before reading input.
int() int([x])
int(x, base=10)

Convert a number or string to an integer.
If x is not a number or if base is given, then x must be a string

>>> int('8')
8
>>> int(8.0)
8
>>> int('8')
8
>>> int('1000',2)
8
>>> int('FF',16)
255

 

Go Top

isinstance() isinstance(obj, class_or_tuple) Return whether an object is an instance of a class or of a subclass thereof
issubclass() issubclass(cls, class_or_tuple) Return whether 'cls' is a derived from another class or is the same class
iter() iter(iterable)
iter(callable, sentinel)
Get an iterator from an object.  In the first form, the argument must supply its own iterator, or be a sequence. In the second form, the callable is called until it returns the sentinel
len() len(obj) Return the number of items in a container
list() list(iterable=()) Built-in mutable sequence. If no argument is given, the constructor creates a new empty list. The argument must be an iterable if specified
locals() locals() Return a dictionary containing the current scope's local variables
map() map(func, *iterables) Make an iterator that computes the function using arguments from each of the iterables.  Stops when the shortest iterable is exhausted.
max() max(iterable, *[, default=obj, key=func])
max(arg1, arg2, *args, *[, key=func])
With a single iterable argument, return its biggest item. The default keyword-only argument specifies an object to return if the provided iterable is empty. With two or more arguments, return the largest argument
memoryview() memoryview(object)

Create a new memoryview object which references the given object

>>> randomByteArray = bytearray('ABC', 'utf-8')
>>> mv=memoryview(randomByteArray)
>>> for m in mv:
...    print(m)
...
65
66
67

Go Top

min() min(iterable, *[, default=obj, key=func])
min(arg1, arg2, *args, *[, key=func])
With a single iterable argument, return its smallest item. The default keyword-only argument specifies an object to return if the provided iterable is empty. With two or more arguments, return the smallest argument
next() next(iterator[, default]) Return the next item from the iterator. If default is given and the iterator is exhausted, it is returned instead of raising StopIterationith two or more arguments, return the smallest argument
object() object() Return a new featureless object. object is a base for all classes. It has the methods that are common to all instances of Python classes. This function does not accept any arguments
oct() oct(number) Return the octal representation of an integer
open() open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None) Open file and return a stream.  Raise OSError upon failure.

file is either a text or byte string giving the name

mode is an optional string that specifies the mode in which the file is opened.

'r' which means open for reading (default)
'w' for writing
'x' for creating and writing to a new file
'a' for appending
ord() ord(c) Return the Unicode code point for a one-character string
pow() pow(x, y, z=None) Equivalent to x**y (with two arguments) or x**y % z (with three arguments)
print() print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False) Prints the values to a stream, or to sys.stdout by default.

file:  a file-like object (stream); defaults to the current sys.stdout.
sep:   string inserted between values, default a space.
end:   string appended after the last value, default a newline.
flush: whether to forcibly flush the stream.
property() property(fget=None, fset=None, fdel=None, doc=None)

fget : function to be used for getting an attribute value
fset : function to be used for setting an attribute value
fdel :function to be used for del'ing an attribute
doc : docstring

Go Top

range() range(stop)
range(start, stop[, step])

range(stop) -> list of integers
    range(start, stop[, step]) -> list of integers
    
    Return a list containing an arithmetic progression of integers.
    range(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0.
    When step is given, it specifies the increment (or decrement).
 

repr() repr(obj)

Return the canonical string representation of the object

Go Top

reversed() reversed(sequence)

Return a reverse iterator over the values of the given sequence/

>>> L=[1,2]
>>> for l in L:
...    print(l)
...
1
2
>>> for l in reversed(L):
...    print(l)
...
2
1

round() round(number, ndigits

Round a number to a given precision in decimal digits

>>> round(8,2)
8
>>> round(8.123,2)
8.12
>>> round(8.123)
8

set() set()
set(iterable)

Build an unordered collection of unique elements

Go Top

setattr() setattr(obj, name, value) Sets the named attribute on the given object to the specified value.
setattr(x, 'y', v) is equivalent to ``x.y = v''
slice() slice(stop)
slice(start, stop[, step])
Create a slice object.  This is used for extended slicing (e.g. a[0:10:2])
sorted() sorted(iterable)
sorted(iterable, key=None, reverse=False)
Return a new list containing all items from the iterable in ascending order.

A custom key function can be supplied to customize the sort order, and the reverse flag can be set to request the result in descending order.
staticmethod() staticmethod(function) Convert a function to be a static method
str() str(object='')
str(bytes_or_buffer[, encoding[, errors]])
Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.__str__() (if defined) or repr(object). encoding defaults to sys.getdefaultencoding(). errors defaults to 'strict'.
sum() sum(iterable, start=0) Return the sum of a 'start' value (default: 0) plus an iterable of numbers

When the iterable is empty, return the start value. This function is intended specifically for use with numeric values and may reject non-numeric types
super() super()
super(type)
super(type, obj)
super(type, type2)
The super() builtin returns a proxy object that allows you to refer parent class by 'super'
tuple() tuple(iterable=()) Built-in immutable sequence.

If no argument is given, the constructor returns an empty tuple. If iterable is specified the tuple is initialized from iterable's items. If the argument is a tuple, the return value is the same object.
type() type(object) Return the object's type
vars() vars([object]) Without arguments, equivalent to locals(). With an argument, equivalent to object.__dict__.
zip() zip(iter1 [,iter2 [...]]) Return a zip object whose .__next__() method returns a tuple where the i-th element comes from the i-th iterable argument.  The .__next__() method continues until the shortest iterable in the argument sequence is exhausted and then it raises StopIteration.
User defined Functions

def FunctionName([parameter1][, parameter2 ...]):
   statements
   [return result1[,result2] ....]

Starts with def and take note the colon : at the end, optionally ends with return statement

Functions without return statement will have resulting value of None

return leaves the current function call with the expression list (or None) as return value

 


## Example function with no parameters
def MyFunction1():


## Example function with 1 parameter
def MyFunction1(p1):


## Example function with 1 parameter and 1 return value
def MyFunction2(p1):
   result=p1**2
   return result

## Example function with 1 parameter
## and multiple return values
## multiple values returned as data type Tuple
>>> def ConvertSeconds(totalseconds):
...    minutes = totalseconds//60
...    seconds = totalseconds - minutes*60
...    return minutes, seconds
...
>>> print(ConvertSeconds(130))
(2, 10)
>>> result=ConvertSeconds(130)
>>> print(result)
(2, 10)
>>> print(type(result))
<type 'tuple'>
>>>


## Example to specify specific data types
## for the arguments
>>> def mysum(x: int, y: int):
...     result = x+y
...     return result
...
>>> mysum(1,2)
3

## Example to specify specific data type
## for the function return value
>>> def myfloatsum(x: int, y: int) -> float:
...    result = float(x+y)
...    return(result)
...
>>> myfloatsum(1,2)
3.0

Anonymous inline Functions : Lambda

lambda [parameters]: expression

Example, generate a list of squares of numbers 1-10:

>>> squares = map(lambda x: x**2, range(10))
>>> print(squares)
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

Go Top

Output Formatting Examples

Method 1

% formatting operator

>>> print('...%s...' % 'Hello')
...Hello...

>>> var1=20
>>> var2=-10
>>> print("%8.2f\t%8.2f" % (var1,var2)
)

    + 2 0 . 0 0
         
    - 1 0 . 0 0

 

 

Go Top

Method 2

string.format() method

Syntax:

   "[string_literals]{replacement_field}[string_literals]".format(args)

{replacement_field}

   { [field_name] : ![conversion] : [format_spec] }

field_name : positional args (0,1,2 etc) or variable name
converstion : r,s,a which calls repr(), str() or ascii() respectively
format_spec: see below

 

Example 1

>>> print('...{:s}...'.format('Hello'))
...Hello...

or

>>> strHello='Hello'
>>> print('...{:s}...'.format(strHello))
...Hello...

or

>>> print('...{0}...'.format(strHello))
...Hello...

Example 2

>>> var1=20
>>> var2=-10.123
>>> print("{0:8.2f}\t{1:8.2f}".format(var1,var2))

    + 2 0 . 0 0
         
    - 1 0 . 0 0

 

 

Example 3

name="Tom"
age="30"
print("Your name is {} and you are {} years old".format(name,age)

Example 4

>>> name="Tom"
>>> age="30"
>>> print("Your name is {} and you are {} years old".format(name,age))
Your name is Tom and you are 30 years old
>>> print("Your name is {0} and you are {1} years old".format(name,age))
Your name is Tom and you are 30 years old
>>> print("Your name is {1} and you are {0} years old".format(age,name))
Your name is Tom and you are 30 years old
>>> print("Your name is {pName} and you are {pAge} years old".format(pName=name,pAge=age))
Your name is Tom and you are 30 years old
>>> print("Your name is {pName} and you are {pAge} years old".format(pAge=age,pName=name))
Your name is Tom and you are 30 years old

 

Go Top

Method 3

formatted string literals (f-strings)

Syntax:

     f"[string_literals]{replacement_field}[string_literals]"

{replacement_field}

     { [field_name] : ![conversion] : [format_spec] }

field_name : variable name
converstion : r,s,a which calls repr(), str() or ascii() respectively
format_spec: see below
 

>>> strHello='Hello'
>>> print(f'...{strHello:s}...')
...Hello...

>>> var1=20
>>> var2=-10

>>> print(f'{var1:+8.2f}\t{var2:+8.2f}')

 

    + 2 0 . 0 0
         
    - 1 0 . 0 0

 

 

>>> print(f'{var1:-8.2f}\t{var2:-8.2f}')

      2 0 . 0 0
         
    - 1 0 . 0 0

 

 

>>> print(f'{var1:_<8.2f}\t{var2:_>8.2f}')

2 0 . 0 0 _ _ _
         
 _ _ - 1 0 . 0 0

 

 

>>> print(f'{var1:08.2f}\t{var2:08.2f}')

 0 0 0 2 0 . 0 0
         
 - 0 0 1 0 . 0 0

 

 

>>> print(f'{var1:_<8d}\t{var2:_>8d}')

 2 0 _ _ _ _ _ _
         
_ _ _ _ _ - 1 0

 

 

>>> print(f'{var1:_<8b}\t{var2:_>8o}')

 1 0 1 0 0 _ _ _
         
_ _ _ _ _ - 1 2

 

 

>>> print(f'{var1:_<#8b}\t{var2:_>#8o}')

0 b 1 0 1 0 0  
         
      - 0 o 1 2

 

 

 Go Top

Format Specifier (further reference here)

 

format_spec     ::= [[fill]align][sign][#][0][width][grouping_option][.precision][type]

fill            ::= <any character>
align           ::= "<" | ">" | "=" | "^"
sign            ::= "+" | "-" | " "
width           ::= digit+
grouping_option ::= "_" | ","
precision       ::= digit+
type            ::= "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"

To use variable as width use a nested {} within the replacement field

Example
>>> M=27
>>> print("{:-^{}s}".format('WELCOME',M))
----------WELCOME----------


< align left
> align right
= for numeric types, places padding after sign but before digit e.g. +000000120
^ center align

+ sign should be used for both positive and negative
- sign should be used only for negative
'' space should be used for positive, - should be used for negative

b Binary format
c Character format
d Decimal integer, base 10
e Exponent notation with lowecase e, precision is 6
E Exponent notation with uppercase E
f fixed point notation, default precision 6
F same as F, but converts 'nan' to 'NAN', 'inf' to 'INF'
g General format
G same as g but switches to 'E' if number is too large
n Number format, uses current local setting for number separator
o Octal format, base 8
s String format
x Hex format using lowercase
X Hex format using UPPERCASE
% Percentage format.  Multiples number by 100, uses f format and appends %


 Go Top

String Slicing Examples
S[i:j:k]
- return slice from index i, up but excluding index j, index step k

 


S[i]
- return char at index i

S[i:j]
- return slice from index i to (but excluding) index j

S[i:]
- return slice from index i to the end of string

S[-1]
- return slice last char from end of string (first from back)

S[::-1]
- return the string in reverse

>>> S="Hello, World!"
>>> S[2:5:1]
'llo'
>>> S[0:10:2]
'Hlo o'

>>> S[4]
'o'

>>> S[1:4]
'ell'

>>> S[7:]
'World!'

>>> S[-1]
'!'

>>> S[::-1]
'!dlroW ,olleH'

Go Top

String methods Examples 
str.capitalize()

string with its first character capitalized and the rest lowercased


str.casefold()

Return a casefolded copy of the string. Casefolded strings may be used for caseless matching.  Different from converting to lowercase, stronger, more agressive,


str.center(width[, fillchar])

Return centered in a string of length width. Padding is done using the specified fillchar (default is an ASCII space). The original string is returned if width is less than or equal to len(s


str.count(sub[, start[, end]])

Return the number of non-overlapping occurrences of substring sub in the range [start, end]. Optional arguments start and end are interpreted as in slice notation.


str.encode(encoding="utf-8", errors="strict")

Return an encoded version of the string as a bytes object. Default encoding is 'utf-8'


str.endswith(suffix[, start[, end]])

Return True; if the string ends with the specified suffix, otherwise return . suffix can also be a tuple of suffixes to look for. With optional start, test beginning at that position. With optional end, stop comparing at that position


str.expandtabs(tabsize=8)

Return a copy of the string where all tab characters are replaced by one or more spaces, depending on the current column and the given tab size. Tab positions occur every tabsize characters (default is 8)


str.find(sub[, start[, end]])

Return the lowest index in str where substring sub is found,
such that sub is contained within S[start:end].  Optional
arguments start and end are interpreted as in slice notation.
Return -1 on failure.


str.format(*args,**kwargs)

Return a formatted version of str, using substitutions from args and kwargs.  The substitutions are identified by braces ('{' and '}').


str.format_map(mapping)

Similar to "str.format(**mapping)", except that "mapping" is used directly and not copied to a "dict".  This is useful if for example "mapping" is a dict subclass:


str.index(sub[, start[, end]])

Return the lowest index in str where substring sub is found,
such that sub is contained within S[start:end].  Optional
arguments start and end are interpreted as in slice notation.
Raises ValueError when the substring is not found.


str.isalnum()

Return true if all characters in the string are alphanumeric and there is at least one character, false otherwise.  A character "c" is alphanumeric if one of the following returns "True": "c.isalpha()", "c.isdecimal()", "c.isdigit()", or "c.isnumeric()".


str.isalpha()

Return true if all characters in the string are alphabetic and there is at least one character, false otherwise.  Alphabetic characters are those characters defined in the Unicode character database as ôLetterö, i.e., those with general category property being one of ôLmö, ôLtö, ôLuö, ôLlö, or ôLoö.  Note that this is    different from the Alphabetic property defined in the Unicode Standard.


str.isascii()

Return true if the string is empty or all characters in the string are ASCII, false otherwise. ASCII characters have code points in the range U+0000-U+007F.


str.isdecimal()

Return true if all characters in the string are decimal characters and there is at least one character, false otherwise. Decimal characters are those that can be used to form numbers in base 10, e.g. U+0660, ARABIC-INDIC DIGIT ZERO. 


str.isdigit()

Return true if all characters in the string are digits and there is at least one character, false otherwise.  Digits include decimal characters and digits that need special handling, such as the compatibility superscript digits. This covers digits which cannot be used to form numbers in base 10, like the Kharosthi numbers.


str.isidentifier()

Return true if the string is a valid identifier according to the language definition, section Identifiers and keywords.  Use "keyword.iskeyword()" to test for reserved identifiers such as "def" and "class".


str.islower()

Return true if all cased characters [4] in the string are lowercase and there is at least one cased character, false otherwise


str.isnumeric()

Return true if all characters in the string are numeric characters, and there is at least one character, false otherwise. Numeric characters include digit characters, and all characters that have the Unicode numeric value property


str.isprintable()

Return true if all characters in the string are printable or the string is empty, false otherwise. Nonprintable characters are those characters defined in the Unicode character database as “Other” or “Separator”, excepting the ASCII space (0x20) which is considered printable


str.isspace()

Return true if there are only whitespace characters in the string and there is at least one character, false otherwise


str.istitle()

Return true if the string is a titlecased string and there is at least one character, for example uppercase characters may only follow uncased characters and lowercase characters only cased ones. Return false otherwise


str.isupper()

Return true if all cased characters [4] in the string are uppercase and there is at least one cased character, false otherwise


str.join(iterable)

Return a string which is the concatenation of the strings in *iterable*. A "TypeError" will be raised if there are any non- string values in *iterable*, including "bytes" objects.  The separator between elements is the string providing this method.


str.ljust(width[, fillchar])

Return the string left justified in a string of length *width*. Padding is done using the specified *fillchar* (default is an ASCII space). The original string is returned if *width* is less than or equal to "len(s)".


str.lower()

Return a copy of the string with all the cased characters [4] converted to lowercase.


str.lstrip([chars])

Return a copy of the string with leading characters removed. The chars argument is a string specifying the set of characters to be removed. If omitted or None;, the chars argument defaults to removing whitespace. The chars argument is not a prefix; rather, all combinations of its values are stripped.


static str.maketrans(x[, y[, z]])

This static method returns a translation table usable for "str.translate()".  If there is only one argument, it must be a dictionary mapping Unicode ordinals (integers) or characters (strings of length 1) to Unicode ordinals, strings (of arbitrary lengths) or "None". Character keys will then be converted to ordinals. If there are two arguments, they must be strings of equal length, and in the resulting dictionary, each character in x will be mapped to the character at the same position in y.  If there is a third argument, it must be a string, whose characters will be mapped to "None" in the result.


str.partition(sep)

Split the string at the first occurrence of *sep*, and return a 3-tuple containing the part before the separator, the separator itself, and the part after the separator.  If the separator is not found, return a 3-tuple containing the string itself, followed by two empty strings.


str.replace(old, new[, count])

Return a copy of the string with all occurrences of substring *old* replaced by *new*.  If the optional argument *count* is given, only the first *count* occurrences are replaced.


str.rfind(sub[, start[, end]])

Return the highest index in the string where substring *sub* is found, such that *sub* is contained within "s[start:end]". Optional arguments *start* and *end* are interpreted as in slice notation.  Return "-1" on failure.


str.rindex(sub[, start[, end]])

Like "rfind()" but raises "ValueError" when the substring *sub* is not found.


str.rjust(width[, fillchar])


Return the string right justified in a string of length *width*. Padding is done using the specified *fillchar* (default is an ASCII space). The original string is returned if *width* is less than or equal to "len(s)".


str.rpartition(sep)


Split the string at the last occurrence of *sep*, and return a 3-tuple containing the part before the separator, the separator itself, and the part after the separator.  If the separator is not found, return a 3-tuple containing two empty strings, followed by the string itself.


str.rsplit(sep=None, maxsplit=-1)

Return a list of the words in the string, using *sep* as the delimiter string. If *maxsplit* is given, at most *maxsplit* splits are done, the *rightmost* ones.  If *sep* is not specified or "None", any whitespace string is a separator.  Except for splitting from the right, "rsplit()" behaves like "split()" which is described in detail below.


str.rstrip([chars])

Return a copy of the string with trailing characters removed.  The *chars* argument is a string specifying the set of characters to be removed.  If omitted or "None", the *chars* argument defaults to removing whitespace.  The *chars* argument is not a suffix; rather, all combinations of its values are stripped:



str.split(sep=None, maxsplit=-1)

Return a list of the words in the string, using *sep* as the delimiter string.  If *maxsplit* is given, at most *maxsplit* splits are done (thus, the list will have at most "maxsplit+1" elements).  If *maxsplit* is not specified or "-1", then there is no limit on the number of splits (all possible splits are made).

If *sep* is given, consecutive delimiters are not grouped together and are deemed to delimit empty strings (for example, "'1,,2'.split(',')" returns "['1', '', '2']").  The *sep* argument may consist of multiple characters (for example, "'1<>2<>3'.split('<>')" returns "['1', '2', '3']"). Splitting an empty string with a specified separator returns "['']".

If *sep* is not specified or is "None", a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace.  Consequently, splitting an empty string or a string consisting of just whitespace with a "None" separator returns "[]".


str.splitlines([keepends])

Return a list of the lines in the string, breaking at line boundaries.  Line breaks are not included in the resulting list unless *keepends* is given and true.

This method splits on the following line boundaries.  In particular, the boundaries are a superset of *universal newlines*.
 

\n : Line Feed
\r : Carriage Return
\r\n : Carriage Return + Line Feed
\v or \x0b : Line Tabulation
\f or \x0c : Form Feed
\x1c : File Separator
\x1d : Group Separator
\x1e : Record Separator
\x85 : Next Line
\u2028 : Line Separator
\u2029 : Paragraph Separator

Unlike "split()" when a delimiter string *sep* is given, this method returns an empty list for the empty string, and a terminal line break does not result in an extra line:


str.startswith(prefix[, start[, end]])


Return "True" if string starts with the *prefix*, otherwise return "False". *prefix* can also be a tuple of prefixes to look for. With optional *start*, test string beginning at that position. With optional *end*, stop comparing string at that position.


str.strip([chars])

Return a copy of the string with the leading and trailing characters removed. The *chars* argument is a string specifying the set of characters to be removed. If omitted or "None", the *chars* argument defaults to removing whitespace. The *chars* argument is not a prefix or suffix; rather, all combinations of its values are stripped:


The outermost leading and trailing *chars* argument values are stripped from the string. Characters are removed from the leading end until reaching a string character that is not contained in the set of characters in *chars*. A similar action takes place on the trailing end. For example:


str.swapcase()

Return a copy of the string with uppercase characters converted to lowercase and vice versa. Note that it is not necessarily true that "s.swapcase().swapcase() == s".


str.title()

Return a titlecased version of the string where words start with an  uppercase character and the remaining characters are lowercase.


str.translate(table)

Return a copy of the string in which each character has been mapped through the given translation table.  The table must be an object that implements indexing via "__getitem__()", typically a *mapping* or *sequence*.  When indexed by a Unicode ordinal (an integer), the table object can do any of the following: return a Unicode ordinal or a string, to map the character to one or more other characters; return "None", to delete the character from the return string; or raise a "LookupError" exception, to map the character to itself.

You can use "str.maketrans()" to create a translation map from character-to-character mappings in different formats.


str.upper()

Return a copy of the string with all the cased characters [4] converted to uppercase. 


str.zfill(width)

Return a copy of the string left filled with ASCII "'0'" digits to make a string of length *width*. A leading sign prefix ("'+'"/"'-'") is handled by inserting the padding *after* the sign character rather than before. The original string is returned if *width* is less than or equal to "len(s)".

str.capitalize()

>>> 'hello'.capitalize()
'Hello'

str.casefold()

>>> firstString = "der Fluß"
>>> secondString = "der Fluss"
>>> firstString.casefold()
'der fluss'
>>> secondString.casefold()
'der fluss'

str.center()

>>> 'Hello'.center(20,'_')
'_______Hello________'

str.count()

>>> "abracadabra".count("ab",0)
2

str.encode()

>>> "pythön!".encode()
b'pyth\xc3\xb6n!'
# the b prefix means bytecode

str.endswith()

>>> "Friend".endswith("end")
True
>>> "Friendship".endswith("end")
False

with start parameter:

>>> "Your Friend".endswith("end",8)
True
>>> "My Friend".endswith("end",8)
False

str.expandtabs()

>>> "Name\tAddress\tTel".expandtabs()
'Name    Address Tel'
>>> "Name\tAddress\tTel".expandtabs(tabsize=10)
'Name      Address   Tel'

str.format() example here

str.format_map()
   >>> class Default(dict):
   ...     def __missing__(self, key):
   ...         return key
   ...
   >>> '{name} was born in {country}'.format_map(Default(name='Guido'))
   'Guido was born in country' 

str.index()

>>> S="Hello, world!"
>>> S.index(",")
5
>>> S.index(",",0,10)
5
>>> S.index(",",10)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: substring not found

str.isalnum()

>>> "abc123".isalnum()
True
>>> "a12345"
.isalnum()
True
>>> "123456"
.isalnum()
True
>>> "abc123!"
.isalnum()
False

str.isalpha()

>>> "abc".isalpha()
True
>>> "abc123"
.isalpha()
False

str.isascii()

>>> chr(0).isascii()
True
>>> chr(127)
.isascii()
True
>>> chr(128)
.isascii()
False

str.rstrip()
>>> '   spacious   '.rstrip()
'   spacious'
>>> 'mississippi'.rstrip('ipz')
'mississ'

str.split()

>>> '1,2,3'.split(',')
['1', '2', '3']
>>> '1,2,3'.split(',', maxsplit=1)
['1', '2,3']
>>> '1,2,,3,'.split(',')
['1', '2', '', '3', '']
>>> '1 2 3'.split(maxsplit=1)
['1', '2 3']
>>> '   1   2   3   '.split()
['1', '2', '3']

str.splitlines()
>>> 'ab c\n\nde fg\rkl\r\n'.splitlines()
['ab c', '', 'de fg', 'kl']
>>> 'ab c\n\nde fg\rkl\r\n'.splitlines(keepends=True)
['ab c\n', '\n', 'de fg\r', 'kl\r\n']

str.strip()
>>> '   spacious   '.strip()
'spacious'
>>> 'www.example.com'.strip('cmowz.')
'example'


str.title()
>>> 'Hello world'.title()
'Hello World'

str.zfill()
>>> "42".zfill(5)
'00042'
>>> "-42".zfill(5)
'-0042'


 

 

 

 

 

 

 

 

 

 

Go Top

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Go Top

 

 

 

 

 

 

Go Top

List
 
Initialization Examples Other List examples

eg.1

>>> L = list()
>>> L
[]
>>> L.append(1)
>>> L.append(2)
>>> L
[1, 2]

When initialized as empty list with list(), we CANNOT add items by L[index] = value.

eg. 2

>>> L = list("Hello")
>>> L
['H', 'e', 'l', 'l', 'o']

eg. 3

>>> L  = [1,2,3]
>>> L
[1, 2, 3]

eg. 4

>>> L = [] + [1,2,3]
>>> L
[1, 2, 3]
>>> L = [1,2] + [3,4]
>>> L
[1, 2, 3, 4]

eg. 5

>>> L=[11,33,44]
>>> L.insert(1,22)
>>> L
[11, 22, 33, 44]

eg. 6 - Initialize empty list if it does not already exist

if (L is not None):
   L = list()
L.append("apple")


 

e.g. - local all list index where the item equals specific value

>>> L=['a','a','b','d']
>>> NL=[i for i in range(len(L)) if L[i]=='a']
>>> NL
[0, 1]

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Go Top

Methods Examples

list.append(x)

Add an item to the end of the list. Equivalent to a[len(a):] = [x].


list.clear()

Remove all items from the list. Equivalent to del a[:].

list.copy()

Return a shallow copy of the list. Equivalent to a[:].

list.count(x)

Return the number of times x appears in the list.

list.extend(iterable)

Extend the list by appending all the items from the iterable. Equivalent to a[len(a):] = iterable.

list.index(x[, start[, end]])

Return zero-based index in the list of the first item whose value is equal to x. Raises a ValueError if there is no such item.

The optional arguments start and end are interpreted as in the slice notation and are used to limit the search to a particular subsequence of the list. The returned index is computed relative to the beginning of the full sequence rather than the start argument.

list.insert(i, x)

Insert an item at a given position. The first argument is the index of the element before which to insert, so a.insert(0, x) inserts at the front of the list, and a.insert(len(a), x) is equivalent to a.append(x).

list.pop([i])

Remove the item at the given position in the list, and return it. If no index is specified, a.pop() removes and returns the last item in the list. (The square brackets around the i in the method signature denote that the parameter is optional, not that you should type square brackets at that position. You will see this notation frequently in the Python Library Reference.)

list.remove(x)

Remove the first item from the list whose value is equal to x. It raises a ValueError if there is no such item.

list.reverse()

Reverse the elements of the list in place.

list.sort(key=None, reverse=False)

Sort the items of the list in place (the arguments can be used for sort customization, see sorted() for their explanation).  list.sort() does not return a value, but sorts the items in place.  To see the result, call the sort method first and then use the list later

Example data

>>> fruits=['orange','apple','pear','banana','kiwi','apple','banana']

.append() example

>>> fruits.append('grape')
>>> fruits
['banana', 'apple', 'kiwi', 'banana', 'pear', 'apple', 'orange', 'grape']

.count()  example

>>> fruits.count('apple')
2

.index()  example
>>> fruits.index('banana')
3
>>> # Find next banana starting a position 4
>>> fruits.index('banana', 4) 

.insert() example

>>> fruits.insert(1,"grape")
>>> print(fruits)
['orange', 'grape', 'apple', 'pear', 'banana', 'kiwi', 'apple', 'banana']

.pop() example

>>> fruits.pop()
'pear'

.reverse() example

>>> fruits.reverse()
>>> fruits
['banana', 'apple', 'kiwi', 'banana', 'pear', 'apple', 'orange']

.sort() examples

>>> # sort using default sort order
>>> fruits.sort()
>>> fruits
['apple', 'apple', 'banana', 'banana', 'grape', 'kiwi', 'orange', 'pear']
>>> # sort using the length of items as key
>>> fruits.sort(key=len)
>>> print(fruits)
['kiwi', 'pear', 'apple', 'apple', 'banana', 'banana', 'orange']
>>> # sort in reverse order using length of items as key
>>> fruits.sort(key=len,reverse=True)
>>> print(fruits)
['orange', 'banana', 'banana', 'apple', 'apple', 'pear', 'kiwi']

 

List Comprehension

[ expression for variable in sequence ] 

Creates a new list based on the given sequence, each element is the result of the given expressoin

[ expression for variable in sequence if condition ]

Creates a new list based on the given sequence.  Each element is the result of the given expression; elements only get added if the condition is true

 

Examples

>>> xfive = [x*5 for x in range(1,13)]
>>> xfive
[5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60]

 

>>> evenxfive= [x*5 for x in range(1,13) if x%2==0]
>>> evenxfive
[10, 20, 30, 40, 50, 60]

Go Top

Dictionary operations Examples
Initialization

D = dict()

D = dict(one=1,two=2,three=3)

D = {'one':1, 'two':2}

D['one'] = 1
D['two'] = 2

D=dict([('one',1),('two',2)])

D=dict(zip(['one', 'two', 'three'], [1, 2, 3]))

keyList=['one','two','three']
valList=[1,2,3]
D=dict(zip(keyList,valList))


Go Top

Iteration

D=dict(one=1,two=2,three=3)

iterating by the Dictionary keys:-

for k in D.keys():
     # process with key-k, value=D[k]

or just:

for k in D:
    # process with key=k, value=D[k]

 

iterating by the Dictionary values:

for v in D.values():
     # process each value

 

iterating by the Dictionary key,value pair:-

for k,v in D.items():
     # process items with key=k, value=v

 Go Top

Functions for Dictionaries  Examples

len(d)

   Return the number of items in the dictionary *d*.


dict(*kwargs)

   Return a new dictionary initialized from an optional positional
   argument and a possibly empty set of keyword arguments.


iter(d)

   Return an iterator over the keys of the dictionary. 
   This is a shortcut for "iter(d.keys())"
 

len()
>>> a = dict(one=1, two=2, three=3)
>>> len(a)
3

dict()
>>> a = dict(one=1, two=2, three=3)
>>> c = dict(zip(['one', 'two', 'three'], [1, 2, 3]))
>>> d = dict([('two', 2), ('one', 1), ('three', 3)])
>>> e = dict({'three': 3, 'one': 1, 'two': 2})


 

Go Top

Dictionary methods Examples

D.clear()

Remove all items from the dictionary.

D.copy()

Return a shallow copy of the dictionary.

D.fromkeys(seq[, value])

Create a new dictionary with keys from *seq* and values set to  *value*. "fromkeys()" is a class method that returns a new dictionary.  *value* defaults to "None".

D.get(key[, default])

Return the value for *key* if *key* is in the dictionary, else *default*. If *default* is not given, it defaults to "None", so that this method never raises a "KeyError".

D.items()

      Return a new view of the dictionaryÆs items ("(key, value)"
      pairs). See the documentation of view objects.

D.keys()

      Return a new view of the dictionaryÆs keys.  See the
      documentation of view objects.

D.pop(key[, default])

      If *key* is in the dictionary, remove it and return its value,
      else return *default*.  If *default* is not given and *key* is
      not in the dictionary, a "KeyError" is raised.

D.popitem()

      Remove and return a "(key, value)" pair from the dictionary.
      Pairs are returned in LIFO (last-in, first-out) order.

      "popitem()" is useful to destructively iterate over a
      dictionary, as often used in set algorithms.  If the dictionary
      is empty, calling "popitem()" raises a "KeyError".

      Changed in version 3.7: LIFO order is now guaranteed.
      In prior  versions, "popitem()" would return an arbitrary
      key/value pair.

D.setdefault(key[, default])

      If *key* is in the dictionary, return its value.  If not, insert
      *key* with a value of *default* and return *default*.  *default*
      defaults to "None".

D.update([other])

      Update the dictionary with the key/value pairs from *other*,
      overwriting existing keys.  Return "None".

      "update()" accepts either another dictionary object or an
      iterable of key/value pairs (as tuples or other iterables of
      length two).  If keyword arguments are specified, the  
      dictionary is then updated with those key/value pairs:
     "d.update(red=1, blue=2)".

D.values()

      Return a new view of the dictionaryÆs values.  See the
      documentation of view objects.

 

.clear()
>>> d = dict(one=1, two=2, three=3)
>>> d
{'one': 1, 'two': 2, 'three': 3}
>>> d.clear()
>>> d
{}

.copy()
>>> d=dict(one=1, two=2, three=3)
>>> d
{'one': 1, 'two': 2, 'three': 3}
>>> e=d.copy()
>>> e
{'one': 1, 'two': 2, 'three': 3}
 

Go Top

Classes & Objects
References: help('class')
 

class ClassName[ ] :
    "doc string for the class, accessible by calling the .__doc__ attr"

 

 

Notes:

Functions defined within the class (methods) have self as the first argument, whenever an object calls its method, the object itself is passed as the first argument.

calling a method with a list of n arguments is equivalent to calling the corresponding function with an argument list that is created by inserting the method's object before the first argument

__init__() function is the constructor for the class.  This function gets called whenever a new object of that class is instantiated

__str__() function defines whatt is printed when you call the print() function with the instance of the class as parameter

 

eg.

>>> class Apple:
...    def __init__(self, color, flavor):
...       self.color = color
...       self.flavor = flavor
...    def __str__(self):
...       return "This apple is {} and it is {}".format(self.color,self.flavor)
...
>>> grannysmith = Apple("green","sour")
>>> print(grannysmith)
This apple is green and it is sour

 

 

 

 

 

 

 

 

 Go Top

 

 

 

Sets  
Set operations Examples
Initalization >> myset = {1, 2} # Directly assigning values to a set
>> myset = set()  # Initializing a set
>> myset = set(['a', 'b']) # Creating a set from a list
>> myset
{'a', 'b'}
Add >> myset.add('c')
>> myset
{'a', 'c', 'b'}
>> myset.add('a') # As 'a' already exists in the set, nothing happens
>> myset.add((5, 4))
>> myset
{'a', 'c', 'b', (5, 4)}
 
Update >> myset.update([1, 2, 3, 4]) # update() only works for iterable objects
>> myset
{'a', 1, 'c', 'b', 4, 2, (5, 4), 3}
>> myset.update({1, 7, 8})
>> myset
{'a', 1, 'c', 'b', 4, 7, 8, 2, (5, 4), 3}
>> myset.update({1, 6}, [5, 13])
>> myset
{'a', 1, 'c', 'b', 4, 5, 6, 7, 8, 2, (5, 4), 13, 3}
 
Remove >> myset.discard(10)
>> myset
{'a', 1, 'c', 'b', 4, 5, 7, 8, 2, 12, (5, 4), 13, 11, 3}
>> myset.remove(13)
>> myset
{'a', 1, 'c', 'b', 4, 5, 7, 8, 2, 12, (5, 4), 11, 3}
Set operations - union, intersection, difference >> a = {2, 4, 5, 9}
>> b = {2, 4, 11, 12}
>> a.union(b) # Values which exist in a or b
{2, 4, 5, 9, 11, 12}
>> a.intersection(b) # Values which exist in a and b
{2, 4}
>> a.difference(b) # Values which exist in a but not in b
{9, 5}
Methods  
  add(...)
      Add an element to a set. 
     This has no effect if the element is already present.

  clear(...)
      Remove all elements from this set.

  copy(...)
      Return a shallow copy of a set.

  difference(...)
      Return the difference of two or more sets as a new set.
      (i.e. all elements that are in this set but not the others.)

  difference_update(...)
      Remove all elements of another set from this set.

  discard(...)
      Remove an element from a set if it is a member.
      If the element is not a member, do nothing.

  intersection(...)
      Return the intersection of two sets as a new set.
      (i.e. all elements that are in both sets.)

  intersection_update(...)
      Update a set with the intersection of itself and another.

  isdisjoint(...)
      Return True if two sets have a null intersection.

  issubset(...)
      Report whether another set contains this set.

  issuperset(...)
      Report whether this set contains another set.

  pop(...)
      Remove and return an arbitrary set element.
      Raises KeyError if the set is empty.

  remove(...)
      Remove an element from a set; it must be a member.

      If the element is not a member, raise a KeyError.

  symmetric_difference(...)
      Return the symmetric difference of two sets as a new set.

      (i.e. all elements that are in exactly one of the sets.)

  symmetric_difference_update(...)
      Update a set with the symmetric difference of itself
      and another.

  union(...)
      Return the union of sets as a new set.
      (i.e. all elements that are in either set.)

  update(...)
      Update a set with the union of itself and others.

 

 

Go Top

File Input & Output  

open()

open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)

Open file and return a stream.  Raise OSError upon failure.

 

Mode Meaning
r open for reading (default)
w open for writing, truncating the file first
x create a new file and open it for writing
a open for writing, appending to the end of the file if it exists
b binary mode
t text mode (default)
+ open a disk file for updating (reading and writing)

 

Note: For directory related operation see os module

 

 

example 1 - read file line by line
file=open('list.txt','r')
for line in file:
     line = line.strip('\n')
     print(line)
file.close()

example 2 - write to a file line by line, overwrite target file

file=open('list.txt','w')
file.write("first\n")
file.write("second\n")
file.close



example 3 - append to existing file

file=open('list.txt','a')
file.write('third\n')
file.close

example 4 - read entire file into a string/array

# read whole file into a string
with open('file.txt', 'r') as file:
data = file.read()

# read whole file into a string and strip all newlines '\n','')
with open('file.txt', 'r') as file:
data = file.read().replace('\n','')

# read whole file line by line into an array
with open('file.txt', 'r') as file:
lines = file.readlines()


Go Top

Tuples
Initialization

Tuples may be constructed in a number of ways:

  • Using a pair of parentheses to denote the empty tuple: ()

  • Using a trailing comma for a singleton tuple: a, or (a,)

  • Separating items with commas: a, b, c or (a, b, c)

  • Using the tuple() built-in: tuple() or tuple(iterable)

Accessing

Although you use brackets () to initialize Tuples, when accessing elements of the Tuple, use square brackets [] to slice or obtain value of specific index

e.g.

>>> Numbers=("zero","one","two","three","four")
>>> Numbers[0]
'zero'
>>> Numbers[1:3]
('one', 'two')

 

   
   

Go Top

Miscellaneous  

as

used with import, except and with

import SomeModule as SomeNamespace:

except SomeException as SomeVariable:

with SomeExpression as SomeTarget:

Examples:

>>> import re as regex
>>> if regex.match(r'^\d+[.]\d+{2}$',"192.16"):
...    print("True")
... else:
...    print("False")
...
True

 Go Top

del

del target

Deletion of a target list recursively deletes each target, from left to right.

Deletion of a name removes the binding of that name from the local or global namespace

See also delattr

e.g.

>>> s=['1','2','3','4','5']
>>> del s[3:]
>>> s
['1', '2', '3']

 

 

Go Top

from

used with import, yield

from Module import Identifier [ as identifier ]

yield from Expression

 

 

 

 

 

Go Top

global

is a declaration which holds for the entire current code block. It means that the listed identifiers are to be interpreted as global in scope

Allows you to assign values to a global variable

example

when "global" statement is used:

>>> def myfun():
...    global S
...    S = S + " modified"
...    print("Print from inside function : " + S)
...
>>> S="a global variable"
>>> print(S)
a global variable
>>> myfun()
Print from inside function : a global variable modified

when "global" statement not used

>>> def myfun():
...    S = S + " modified"
...    print("Print from inside function : " + S)
...
>>> S="a global variable"
>>> print(S)
a global variable
>>> myfun()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in myfun
UnboundLocalError: local variable 'S' referenced before assignment

Go Top

nonlocal

Makes the value bound to a variable available to the enclosing function in nested functions. 

Introduced from version 3.8

def outer():
    x = "local"
   
    def inner():
        nonlocal x
        x = "nonlocal"
        print("inner:", x)
   
    inner()
    print("outer:", x)

outer()

output

inner: nonlocal
outer: nonloca

pass

pass is a null operation, when it is executed, nothing happens.  It is useful as a placeholder when a statement is required syntactically, but no code needs to be executed.

 

Examples:

def f(arg):
  pass
  # function that does nothing (yet)

class C:
  pass   
  # class with no methods (yet)

Go Top

raise

the statement to raise an exception

 

eg. 1

if x < 0:
   raise Exception("You entered a negative number")

eg. 2

if not type(n) is int:
  raise TypeError("Not an integer")

e.g. 3

## raise ValueError if the item to be removed
## is not in the list
def RemoveValue(myVal):
    if myVal not in my_list:
        raise ValueError("Value must be in the given list")
    else:
        my_list.remove(myVal)
    return my_list

 Go Top

with

with smthg_that_returns_context_manager as var:
   # process var

The with statement is used to wrap the execution of a block with methods defined by a context manager

A context manager is an object that defines the runtime context to be established when executing a with statement. The context manager handles the entry into, and the exit from, the desired runtime context for the execution of the block of code

eg. 1

# using with statement
with open('filepath', 'w') as file:
    file.write('some data')

# The with statement will ensure the file is closed at the end of the block.
# no need to explicitly close the file.
 

yield

yield <expr>
yield from <expr>

yield expressions and statements are only used when defining a generator function, and are only used in the body of the generator function.

A generator function, is like a normal function but with yield statement instead of a return statement.

The difference is that, while a return statement terminates a function entirely, yield statement pauses the function saving all its states and later continues from there on successive calls.

Examples:

>>> def MyGen():
...    list=range(5)
...    for i in list:
...       yield i*i
...
>>> for x in MyGen():
...    print(x)
...
0
1
4
9
16

 

Go Top