Python Cheat Sheet
Python Cheat Sheet
Python Cheat Sheet
a = [1, 2, 3, 4, 5]
print(' '.join(map(str, a)))
print"in new line"
print('\n'.join(map(str, a)))
end= ” ” statement
The end keyword is used to specify the content that is to be printed at the end of the execution of the
print() function. By default, it is set to “\n”, which leads to the change of line after the execution of print()
statement.
print ("GeeksForGeeks is the best platform for DSA content")
# This print() function ends with "**" as set in the end argumennt.
print ("GeeksForGeeks is the best platform for DSA content", end= "**")
print 8 blank lines
print (8 * "\n")
Lamda Expression
filter()
map() in lambda
The global Keyword
If we want those changes to be reflected in our global variable, instead of making a new local one, all we
have to do is add the global keyword. This allows us to communicate that the fruit variable is indeed a
global variable:
We could also define a global variable within our function and have it be able to be referenced and
accessed anywhere else.
def shopping_list():
global fruit
fruit = ['pineapple', 'grapes', 'apple', 'banana']
shopping_list()
print(fruit)
nonlocal, a keyword which functions very similarly to global, but primarily takes effect when nested in
methods. nonlocal essentially forms an in-between of global and local scope.
Number Data Type in Python
Python supports integers, floating-point numbers and complex numbers. They are defined as int, float,
and complex classes in Python.
Complex numbers are written in the form, x + yj, where x is the real part and y is the imaginary part.
We can use the type() function to know which class a variable or a value belongs to
and isinstance() function to check if it belongs to a particular class.
a = 5
print(type(a))
print(type(5.0))
c = 5 + 3j
print(c + 3)
print(isinstance(c, complex))
In Python, we can represent these numbers by appropriately placing a prefix before that number. The
following table lists these prefixes.
Number System Prefix Save Copy to Evernote
# empty list
my_list = []
# list of integers
my_list = [1, 2, 3]
A list can also have another list as an item. This is called a nested list.
# nested list
my_list = ["mouse", [8, 4, 6], ['a']]
Negative indexing
Python allows negative indexing for its sequences. The index of -1 refers to the last item, -2 to the second
last item and so on.
my_list = ['p','r','o','g','r','a','m','i','z']
Output
print(odd)
print(odd)
Output
[1, 4, 6, 8]
[1, 3, 5, 7]
We can add one item to a list using the append() method or add several items using extend() method.
odd.append(7)
print(odd)
We can also use + operator to combine two lists. This is also called concatenation.
print(["re"] * 3)
Output
we can insert one item at a desired location by using the method insert() or insert multiple items by
squeezing it into an empty slice of a list.
print(odd)
odd[2:2] = [5, 7]
print(odd)
Output
[1, 3, 9]
[1, 3, 5, 7, 9]
print(my_list)
print(my_list)
extend() Add all elements of a list to the another list Also add Multiple items to a list
extend() - Add all elements of a list to the another list. Also add Multiple items to a list
remove() - Removes an item from the list. but shows error if not found
List Comprehension:
# Output: True
print('p' in my_list)
# Output: True
print('c' not in my_list)
Tuples
A tuple in Python is similar to a list. The difference between the two is that we cannot change the
elements of a tuple once it is assigned whereas we can change the elements of a list.
A tuple is created by placing all the items (elements) inside parentheses (), separated by commas.
# Different types of tuples
# Empty tuple
my_tuple = ()
print(my_tuple)
# nested tuple
my_tuple = ("mouse", [8, 4, 6], (1, 2, 3))
print(my_tuple)
Having one element within parentheses is not enough. We will need a trailing comma to indicate that it is,
in fact, a tuple.
# Creating a tuple having one element
my_tuple = ("hello",)
print(type(my_tuple)) # <class 'tuple'>
Indexing of Tuple
We can use the index operator [] to access an item in a tuple, where the index starts from 0.
print(my_tuple[0]) # 'p'
print(my_tuple[5]) # 't'
Slicing
We can access a range of items in a tuple by using the slicing operator colon :.
Changing a Tuple
Unlike lists, tuples are immutable.
This means that elements of a tuple cannot be changed once they have been assigned. But, if the element
is itself a mutable data type like a list, its nested items can be changed. Save Copy to Evernote
We can also assign a tuple to different values (reassignment).
# Output: ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')
print(my_tuple)
# Concatenation
# Output: (1, 2, 3, 4, 5, 6)
print((1, 2, 3) + (4, 5, 6))
# Repeat
# Output: ('Repeat', 'Repeat', 'Repeat')
print(("Repeat",) * 3)
Deleting a Tuple
As discussed above, we cannot change the elements in a tuple. It means that we cannot delete or remove
items from a tuple.
Deleting a tuple entirely, however, is possible using the keyword del.
# In operation
print('a' in my_tuple)
print('b' in my_tuple)
# Not in operation
print('g' not in my_tuple)
We generally use tuples for heterogeneous (different) data types and lists for homogeneous
(similar) data types.
Since tuples are immutable, iterating through a tuple is faster than with list. So there is a slight
performance boost.
Tuples that contain immutable elements can be used as a key for a dictionary. With lists, this is not
possible.
If you have data that doesn't change, implementing it as tuple will guarantee that it remains write-
protected.
String in Python
#first character
print('str[0] = ', str[0])
#last character
print('str[-1] = ', str[-1])
Strings are immutable. This means that elements of a string cannot be changed once they have been
assigned. We can simply reassign different strings to the same name.
We cannot delete or remove characters from a string. But deleting the string entirely is possible using
the del keyword.
# Python String Operations
str1 = 'Hello'
str2 ='World!'
# using +
print('str1 + str2 = ', str1 + str2)
# using *
print('str1 * 3 =', str1 * 3)
# Iterating through a string
count = 0 Save Copy to Evernote
for letter in 'Hello World':
if(letter == 'l'):
count += 1
print(count,'letters found')
We can test if a substring exists within a string or not, using the keyword in.
>>> 'a' in 'program'
True
>>> 'at' not in 'battle'
False
Method Description
endswith() Returns true if the string ends with the specified value
find() Searches the string for a specified value and returns the position of where it was
found
index() Searches the string for a specified value and returns the position of where it was
found
isalpha() Returns True if all characters in the string are in the alphabet
isupper() Returns True if all characters in the string are upper case
partition() Returns a tuple where the string is parted into three parts
replace() Returns a string where a specified value is replaced with a specified value
rfind() Searches the string for a specified value and returns the last position of where it
was found
rindex() Searches the string for a specified value and returns the last position of where it
was found
rpartition() Returns a tuple where the string is parted into three parts
rsplit() Splits the string at the specified separator, and returns a list
split() Splits the string at the specified separator, and returns a list
startswith() Returns true if the string starts with the specified value
swapcase() Swaps cases, lower case becomes upper case and vice versa
zfill() Fills the string with a specified number of 0 values at the beginning
Sets in Python
A set is an unordered collection of items. Every set element is unique (no duplicates) and must be
immutable (cannot be changed).
Creating Python Sets
A set is created by placing all the items (elements) inside curly braces {}, separated by comma, or by using
the built-in set() function.It can have any number of items and they may be of different types (integer, float,
tuple, string etc.). But a set cannot have mutable elements like lists, sets or dictionaries as its elements.
my_set = {1, 2, 3}
print(my_set)
Empty curly braces {} will make an empty dictionary in Python. To make a set without any elements, we
use the set() function .without any argument.
# initialize my_set
my_set = {1, 3}
print(my_set)
# my_set[0]
# if you uncomment the above line
# you will get an error
# TypeError: 'set' object does not support indexing
# add an element
# Output: {1, 2, 3}
my_set.add(2)
print(my_set)
# initialize my_set
my_set = {1, 3, 4, 5, 6}
print(my_set)
# discard an element
# Output: {1, 3, 5, 6}
my_set.discard(4)
print(my_set)
# remove an element
# Output: {1, 3, 5}
my_set.remove(6)
print(my_set)
# discard an element
# not present in my_set
# Output: {1, 3, 5}
my_set.discard(2)
print(my_set)
# remove an element
i
# not present in my_set
# you will get an error.
# Output: KeyError Save Copy to Evernote
my_set.remove(2)
Python has a set of built-in methods that you can use on sets.
Method Description
difference() Returns a set containing the difference between two or more sets
difference_upda Removes the items in this set that are also included in another, specified set
te()
intersection_up Removes the items in this set that are not present in other, specified set(s)
date()
symmetric_diffe inserts the symmetric differences from this set and another
rence_update()
update() Update the set with another set, or any other iterable
Set Membership Test
Save Copy to Evernote
We can test if an item exists in a set or not, using the in keyword.
my_set = set("apple")
Function Description
all() Returns True if all elements of the set are true (or if the set is empty).
any() Returns True if any element of the set is true. If the set is empty, returns False.
enumerate() Returns an enumerate object. It contains the index and value for all the items of the
set as a pair.
sorted() Returns a new sorted list from elements in the set(does not sort the set itself).
Python Dictionary
Python dictionary is an unordered collection of items. Each item of a dictionary has a key/value pair.
# empty dictionary Save Copy to Evernote
my_dict = {}
# using dict()
my_dict = dict({1:'apple', 2:'ball'})
# Output: Jack
print(my_dict['name'])
# Output: 26
print(my_dict.get('age'))
# KeyError
print(my_dict['address'])
# update value
my_dict['age'] = 27
# add item
my_dict['address'] = 'Downtown'
# Dictionary Comprehension
squares = {x: x*x for x in range(6)}
print(squares)
print(odd_squares)
We can test if a key is in a dictionary or not using the keyword in only for the keys and not for the values.
# Membership Test for Dictionary Keys
squares = {1: 1, 3: 9, 5: 25, 7: 49, 9: 81}
# Output: True
print(1 in squares)
# Output: True
print(2 not in squares)
This method is not entirely safe. If an exception occurs when we are performing some operation with the
file, the code exits without closing the file.
try:
f = open("test.txt", encoding = 'utf-8')
# perform file operations
finally:
f.close()
with open("test.txt", encoding = 'utf-8') as f:
# perform file operations
Save Copy to Evernote
We can change our current file cursor (position) using the seek() method. Similarly, the tell() method
returns our current position (in number of bytes).
we can use the readline() method to read individual lines of a file. This method reads a file till the newline,
including the newline character.
>>> f.readlines()
['This is my first file\n', 'This file\n', 'contains three lines\n']
#use strip() to remove \n
Python Directory
>>> os.getcwd()
'C:\\Program Files\\PyScripter'
>>> os.getcwdb()
b'C:\\Program Files\\PyScripter'
Changing Directory
>>> os.chdir('C:\\Python33')
>>> print(os.getcwd())
C:\Python33
>>> print(os.getcwd())
C:\Python33
>>> os.listdir()
['DLLs',
'Doc',
'include',
'Lib',
'libs',
'LICENSE.txt',
'NEWS.txt',
'python.exe',
'pythonw.exe',
'README.txt',
'Scripts',
'tcl',
'Tools']
>>> os.mkdir('test')
>>> os.listdir()
['test']
>>> os.listdir()
['test']
>>> os.rename('test','new_one')
>>> shutil.rmtree('test')
>>> os.listdir()
[]
randomList = ['a', 0, 2]
If no exception occurs, the except block is skipped and normal flow continues(for last value). But if any
exception occurs, it is caught by the except block (first and second values).
Here, we print the name of the exception using the exc_info() function inside sys module. We can see
that a causes ValueError and 0 causes ZeroDivisionError.
try:
num = int(input("Enter a number: "))
assert num % 2 == 0
except:
print("Not an even number!")
else:
reciprocal = 1/num
print(reciprocal)
Python try...finally
The try statement in Python can have an optional finally clause. This clause is executed no matter what,
and is generally used to release external resources.
try:
f = open("test.txt",encoding = 'utf-8')
f open( test.txt ,encoding utf 8 )
# perform file operations
finally: Save Copy to Evernote
f.close()
class Parrot:
# class attribute
species = "bird"
# instance attribute
def __init__(self, name, age):
self.name = name
self.age = age
Methods
class Parrot:
# instance attributes
def __init__(self, name, age):
self.name = name
self.age = age
# instance method
def sing(self, song):
return "{} sings {}".format(self.name, song)
def dance(self):
return "{} is now dancing".format(self.name)
Inheritance
we use the super() function inside the __init__() method. This allows us to run the __init__() method of the
parent class inside the child class.
# parent class
class Bird: Save Copy to Evernote
def __init__(self):
print("Bird is ready")
def whoisThis(self):
print("Bird")
def swim(self):
print("Swim faster")
# child class
class Penguin(Bird):
def __init__(self):
# call super() function
super().__init__()
print("Penguin is ready")
def whoisThis(self):
print("Penguin")
def run(self):
print("Run faster")
peggy = Penguin()
peggy.whoisThis()
peggy.swim()
peggy.run()
Encapsulation
In Python, we denote private attributes using underscore as the prefix i.e single _ or double __.
lass Computer:
def __init__(self):
self.__maxprice = 900
def sell(self):
print("Selling Price: {}".format(self.__maxprice))
c = Computer()
c.sell()
P l hi
Polymorphism
Save Copy to Evernote
class Parrot:
def fly(self):
print("Parrot can fly")
def swim(self):
print("Parrot can't swim")
class Penguin:
def fly(self):
print("Penguin can't fly")
def swim(self):
print("Penguin can swim")
# common interface
def flying_test(bird):
bird.fly()
#instantiate objects
blu = Parrot()
peggy = Penguin()
In the above program, we defined two classes Parrot and Penguin . Each of them have a
common fly() method. However, their functions are different.
To use polymorphism, we created a common interface i.e flying_test() function that takes any object and
calls the object's fly() method. Thus, when we passed the blu and peggy objects in
the flying_test() function, it ran effectively.
Constructors in Python
use __init__(self, variable)
class ComplexNumber:
def __init__(self, r=0, i=0):
self.real = r
self.imag = i
def get_data(self):
print(f'{self.real}+{self.imag}j')
class Base1:
pass
class Base2:
pass
class Base:
pass
class Derived1(Base):
pass
class Derived2(Derived1):
pass
sorted() function:
sorted(iterable, key, reverse)
Note: No matter what iterable is passed in to the sorted() function, it always returns a list.
Save Copy to Evernote
Save Copy to Evernote
Save Copy to Evernote
Save Copy to Evernote