Python Refresher

Quick Python Cheat sheet

·

6 min read

Python Refresher

Python is a high-level, dynamically typed, multiparadigm programming language.

#Check python version
!python --version

Basic Data Types

Numbers

#Integers
p = 5
print(p, type(p))    
#output - 5 <class 'int'>

print(p + 1)   # Addition    #output - 6
print(p - 1)   # Subtraction    #output - 4
print(p * 2)   # Multiplication    #output - 10
print(p ** 2)  # Exponentiation    #output - 25

#compound assignment operator
p += 1      
p *= 2    

#float
y = 2.5
print(type(y))
print(y, y + 1, y * 2, y ** 2)
#output - <class 'float'>
#        2.5 3.5 5.0 6.25

Python does not have unary increment (x++) or decrement (x--) operators.

Booleans

Python implements all of the usual operators for Boolean logic but uses English words rather than symbols.

t, f = True, False
print(type(t))
#output - <class 'bool'>

print(t and f) # Logical AND;    #output - False
print(t or f)  # Logical OR;    #output - True
print(not t)   # Logical NOT;    #output - False
print(t != f)  # Logical XOR;    #output - True

Strings

Strings are a collection of character where each character is again a string of length 1.

Strings are immutable objects.

# String literals can use single quotes or double quotes; it does not matter
hello = 'hello'   
world = "world"   
print(hello, len(hello))
#output - hello 5

# String concatenation
hw = hello + ' ' + world  
print(hw)
#output - hello world

# string formatting
hw12 = '{} {} {}'.format(hello, world, 12)  
print(hw12)
#output - hello world 12

#String Object Methods:
s = "hello"
print(s.capitalize())  # Capitalize a string
print(s.upper())       # Convert a string to uppercase; prints "HELLO"
print(s.rjust(7))      # Right-justify a string, padding with spaces
print(s.center(7))     # Center a string, padding with spaces
print(s.replace('l', '(ell)'))  # Replace all instances of one substring with another
print('  world '.strip())  # Strip leading and trailing whitespace

Data Structures

Python includes several built-in container types: lists, dictionaries, sets, and tuples.

Lists

A list is the Python equivalent of an array but is resizable and can contain elements of different types.

### Create a list
xs = [3, 1, 5, 2.3, "python", "hello Python"]   
print(xs, len(xs))
print(xs[-1]) # Negative index counts from the end of the list; 
#output - [3, 1, 5, 2.3, 'python', 'hello Python'] 6
#         hello Python


### Lists can contain elements of different types
xs[2] = 'foo'  
print(xs)
print("length of xs=", len(xs))
#output - [3, 1, 'foo', 2.3, 'python', 'hello Python']
#         length of xs= 6


### Add a new element to the end of the list
xs.append(5.5) 
print(xs)  
print("length of list=", len(xs))
#output - [3, 1, 'foo', 2.3, 'python', 'hello Python', 5.5]
#         length of list= 7


### Remove and return the last element of the list
x = xs.pop()     
print(xs.pop())
print(x, xs)
print("length of list=", len(xs))
#output - hello Python
#         5.5 [3, 1, 'foo', 2.3, 'python']
#         length of list= 5

Slicing

💡
Python provides concise syntax to access sub lists; this is known as slicing.
nums = list(range(5))    # range is a built-in function that creates a list of integers
print(nums)         # Prints "[0, 1, 2, 3, 4]"
print(type(nums))    # Prints "<class 'list'>"
print(nums[2:4])    # Get a slice from index 2 to 4 (exclusive); prints "[2, 3]"
print(nums[2:])     # Get a slice from index 2 to the end; prints "[2, 3, 4]"
print(nums[:2])     # Get a slice from the start to index 2 (exclusive); prints "[0, 1]"
print(nums[:])      # Get a slice of the whole list; prints "[0, 1, 2, 3, 4]"
print(nums[::2])      # Get a slice of the whole list; prints "[0, 2, 4]"
print(nums[:-1])    # Slice indices can be negative; prints "[0, 1, 2, 3]"
nums[2:4] = [8, 9] # Assign a new sublist to a slice
print(nums)         # Prints "[0, 1, 8, 9, 4]"

Loops

animals = ['cat', 'dog', 'monkey']
for animal in animals:
    print(animal)

#output - cat
#         dog
#         monkey

To access the index of each element within the body of a loop, use the built-in enumerate function:

animals = ['cat', 'dog', 'monkey']
for idx, animal in enumerate(animals):
    print('#{}: {}'.format(idx + 1, animal))

#output - #1: cat
#         #2: dog
          #3: monkey

List comprehensions

💡
If we frequently want to transform one type of data into another
nums = [0, 1, 2, 3, 4]
squares = [x ** 2 for x in nums]
print(squares)

#output - [0, 1, 4, 9, 16]

nums = [0, 1, 2, 3, 4]
even_squares = [x ** 2 for x in nums if x % 2 == 0]
print(even_squares)

#output - [0, 4, 16]

Dictionaries

A dictionary stores (key, value) pairs, similar to a Map in Java.

### Create a new dictionary with some data
d = {'cat': 'cute', 'dog': 'furry'}  
print(type(d))        # Prints "<class 'dict'>"
print(len(d))         # length of the dictionary which is the number of keys in the dictionary
print(d['cat'])       # Get an entry from a dictionary; prints "cute"
print('fox' in d)     # Check if a dictionary has a given key; prints "False"


### Set an entry in a dictionary
d['fish'] = 'wet'    
print(d['fish'])      # Prints "wet"
print(d)            # Prints "{'cat': 'cute', 'dog': 'furry', 'fish': 'wet'}"
print(len(d))        # Prints "3"


### Get an element with a default;
print(d.get('monkey', 'N/A'))  # prints "N/A"
print(d.get('fish', 'N/A'))    # prints "wet"


### Remove an element from a dictionary
del d['fish']        
print(d.get('fish', 'N/A')) # "fish" is no longer a key; prints "N/A"


### Iterating over dictionary
d = {'person': 2, 'cat': 4, 'spider': 8}
for animal, legs in d.items():
    print('A {} has {} legs'.format(animal, legs))
#output - A person has 2 legs
#         A cat has 4 legs
#         A spider has 8 legs


### Dictionary comprehensions
nums = [0, 1, 2, 3, 4]
even_num_to_square = {x: x ** 2 for x in nums if x % 2 == 0}
print(even_num_to_square)
#output - {0: 0, 2: 4, 4: 16}

Sets

A set is an unordered collection of distinct elements.

animals = {'cat', 'dog'}
print('cat' in animals)   # Check if an element is in a set; prints "True"
print('fish' in animals)  # prints "False"


### Add an element to a set
animals.add('fish')     
print('fish' in animals)
print(len(animals))       # Number of elements in a set;


### Remove an element from a set
animals.remove('cat')    
print(len(animals))    


### Iterating over a set 
animals = {'cat', 'dog', 'fish'}
for idx, animal in enumerate(animals):
    print('#{}: {}'.format(idx + 1, animal))


### Set comprehensions  
from math import sqrt
print({int(sqrt(x)) for x in range(30)})
#output - {0, 1, 2, 3, 4, 5}
💡
Iterating over a set has the same syntax as iterating over a list; however, since sets are unordered, you cannot make assumptions about the order in which you visit the elements of the set:

Tuples

A tuple is an (immutable) ordered list of values. A tuple is in many ways similar to a list; one of the most important differences is that tuples can be used as keys in dictionaries and as elements of sets, while lists cannot.

### Create a dictionary with tuple keys
d = {(x, x + 1): x for x in range(10)}  
t = (5, 6)       # Create a tuple
print(type(t))    # Prints "<class 'tuple'>"
print(d[t])       # Prints "5"  
print(d[(1, 2)])    # Prints "1"
💡
'tuple' object does not support item assignment.

Functions

Python functions are defined using the def keyword.

#### defining the function ####
def sign(x):
    if x > 0:
        return 'positive'
    elif x < 0:
        return 'negative'
    else:
        return 'zero'
#### Calling the function ####
for x in [-1, 0, 1]:
    print(sign(x))

#output - negative
#         zero
#         positive



###Function with Arguments
def help(name, flag=False):
    if flag:
        print('HELLO, {}'.format(name.upper()))
    else:
        print('Hello, {}!'.format(name))

help('Bob')
help('Fred', flag=True)

#output - Hello, Bob!
#         HELLO, FRED

Resources

Did you find this article valuable?

Support Sourabh Joshi's Blog by becoming a sponsor. Any amount is appreciated!

Â