Python Cheatsheet

  |   Source

Python Cheatsheet

Python

Types

a = 1           # integer
b = 1.0         # float
c = 1.0e5       # exponential
d = 1.0 + 2.5j  # complex
e = 1 > 0       # boolean
f = 'string'    # string

Lists

a = ['a', 'b', 'c']                # manually initialization
b = list(range(5))                 # initialization through a function
c = [x**2 for x in b]              # initialize through list comprehension
d = [x**2 for x in b if x < 3]     # list comprehension with condition
e = c[0]                           # access element
f = c[1:2]                         # access a slice of the list
g = ['a', 'b'] + ['c']             # list concatenation
h = ['x'] * 5                      # repeat a list
['x', 'y', 'z', 'x'].index('x')    # returns index of an element
'x' in ['x', 'y', 'z', 'x']        # true if the element is in the list
sorted([2, 3, 1, 4], reverse=True) # returns sorted list (big to small)

Dictionaries

a = {'red': 'pula', 'blue': 'asual', 'orange': 'kahel'}  # dictionary
b = a['red']                                             # translate item
c = [value for key, value in a.items()]                  # loop through contents
d = a.get('yellow', 'No translation found!')             # return default

Strings

a = 'pula'                      # assignment
char = a[2]                     # access individual characters
'pula ' + 'asul'                # string concatenation
'1, 2, three'.split(',')        # split string into list
'.'.join(['1', '2', 'tatlo'])   # concatenate list into string

Operators

a = 2             # assignment
a += 1 (*=, /=)   # change and assign
3 + 2             # addition
3 / 2             # integer division (python2) or float division (python3)
3 // 2            # integer division
3 * 2             # multiplication
3 ** 2            # exponent
3 % 2             # remainder
abs(a)            # absolute value
1 == 1            # equal
2 > 1             # larger
2 < 1             # smaller
1 != 2            # not equal
1 != 2 and 2 < 3  # logical AND
1 != 2 or 2 < 3   # logical OR
not 1 == 2        # logical NOT
'a' in b          # test if a is in b
a is b            # test if objects point to the same memory (id)

Control Flow

# if/elif/else
a, b = 1, 2
if a + b == 3:
    print('True')
elif a + b == 1:
    print('False')
else:
    print('?')

# for
a = ['red', 'blue', 'green']
for color in a:
    print(color)

# while
number = 1
while number < 10:
    print(number)
    number += 1

# break
number = 1
while True:
    print(number)
    number += 1
    if number > 10:
        break

# continue
for i in range(20):
    if i % 2 == 0:
        continue
    print(i)

Functions, Classes, Generators, Decorators

# Function
def addition(a1, a2):
    return a1 + a2

x = addition(a1, a2)

# Class
class Point(object):
    def __init__(self, x):
        self.x = x
    def __call__(self):
        print(self.x)

x = Point(3)

# Generators
def firstn(n):
    num = 0
    while num < n:
        yield num
        num += 1

# consume the generator with list comprehension
x = [i for i in firstn(10)]

# Decorators
class myDecorator(object):
    def __init__(self, f):
        self.f = f
    def __call__(self):
        print("call")
        self.f()

@myDecorator
def my_funct():
    print('func')

my_funct()

Types

In [1]:
a = 1           # integer
b = 1.0         # float
c = 1.0e5       # exponential
d = 1.0 + 2.5j  # complex
e = 1 > 0       # boolean
f = 'string'    # string
print('',a,'\n', b,'\n',  c,'\n',  d,'\n',  e,'\n',  f)
 1 
 1.0 
 100000.0 
 (1+2.5j) 
 True 
 string

Lists

In [2]:
# manually initialization
a = ['a', 'b', 'c']                
print(a)
['a', 'b', 'c']
In [3]:
# initialization through a function
b = list(range(5))                 
print(b)
[0, 1, 2, 3, 4]
In [4]:
# initialize through list comprehension
c = [x**2 for x in b]              
print(c)
[0, 1, 4, 9, 16]
In [5]:
# list comprehension with condition
d = [x**2 for x in b if x < 3]     
print(d)
[0, 1, 4]
In [6]:
# access element
e = c[0] 
print(e)
0
In [7]:
# access a slice of the list
f = c[1:2]                         
print(f)
[1]
In [8]:
# list concatenation
g = ['a', 'b'] + ['c']    
print(g)
['a', 'b', 'c']
In [9]:
# repeat a list
h = ['x'] * 5
print(h)
['x', 'x', 'x', 'x', 'x']
In [10]:
# returns index of an element
['x', 'y', 'z', 'x'].index('x')         
Out[10]:
0
In [11]:
# true if the element is in the list
'x' in ['x', 'y', 'z', 'x']
Out[11]:
True
In [12]:
# returns sorted list (big to small)
sorted([2, 3, 1, 4], reverse=True)    
Out[12]:
[4, 3, 2, 1]