Python Cheatsheet
Python Cheatsheet
Python 2.7.x
2.7.x
20140731 Martin Bruchanov, bruxy@regnet.cz
2. Expression statements
FOR cycle
WHILE contition
TRY block
try:
possible runtime error
except [type [as value]]:
error-recovery code
[ else:
suite ]
[ finally:
suite ]
2.1. Classes
class Name:
suite
def __iter__(self):
2.2. Functions
3. Variables
3.1.
Constants
4. Operators
//=
5. Data types
Function
Tuple
List
Dict.
String
Init.
(),tuple() [], list() {}, dict() "",'',str()
clear
copy
count
index
pop
remove
update
5.1.
5.2.
Set
set()
Tuples
t = (), t = tuple() create empty tuple
t = (1, 2, 3) like list, but cant change their values
t[1] access second item, returns 2
t.index(x [, i [, j]]) return index of rst occurrence of
t.count(x) return number of item
Lists
l = [], l = list() empty list
l = [1, 2, 3] one dimensional array
l[1] returns 2, indexing: 10 21 32
l[i:j] slicing from index to
l[i:] slicing from index to end of list
l[i:j:k] slicing with step l[slice(i,j[,k])]
l[-1] last item (rst from back)
0 in [1, 2, 3] False, 1 in [1, 2, 3] True
l = range(5) create list [1, 2, 3, 4, 5]
l = range(start, stop[, step]) given range with step
l = [x**2 for x in range(9)] list from expression result
l.index(item) return index of item in list
l.count(item) total number of occurrences of item
l = ["text", 12, 3, [1, 2]] more types in one list
l2d=[[1, 2, 3], [4, 5, 6], [7, 8, 9]] two-dimensional
list
l2d[1][1] returns 5
list('abc') returns list of chars ['a','b','c']
len(l) return length of list
l.append(value) add value to the list
l.extend([4,5]), list[len(list):]=[4,5], list += [4,5]
append another list
l.insert(i, x), list[i]=x insert at given index
l[:0]=[x,y,z] insert item at front of list
l.remove(value) remove rst occurrence of value
l.pop(i), l.pop() return and remove value, without index last
l.index(x [, i[, j]]) index of rst occur. of x, between to
l.count(x) return number of occurrence of object x
l.sort(key=None, reverse=False) sort list in-place
l.reverse() reverse list in-place
sum(l) return sum of numeric list
5.3.
5.4.
5.5.
Dictionaries
Sets
Strings
[[fill]align][sign][#][0][width][,][.prec][typecode]
7. String methods