Python Cheatsheet

by anupmaurya
0 comment

Python is an interpreted, object-oriented, high-level programming language with dynamic semantics. Its high-level built in data structures, combined with dynamic typing and dynamic binding, make it very attractive for Rapid Application Development, as well as for use as a scripting or glue language to connect existing components together.



print("hello world")
Code language: Python (python)


  • # is used to comment a line in Python

Data Types

CategoryData Type
Numberint, float, complex
Binarybytes, bytearray, memoryview
Setset, frozenset
Sequencelist, tuple, range
  • type() is used to know the data type of a variable

Data casting

Constructor functiondesc
int()constructs an integer from any form of data like string, float or integer
float()constructs a float number from any form of data like string, float or integer
str()constructs a string from any form of data like string, float or integer


In Python, declaring variables is not required. Means you don’t need to specify whether it is an integer or string etc as Python is a dynamically typed language.


Arithmetic Operators+ – * / % ** //
Comparision Operators== != > >= < <=
Bitwise Operators& ^ | ^ ~ << >>
Logical Operators&& || !
Assignment Operators= += -= *= /= %= **= //=
Membership Operatorsin, not in
Identity Operatorsis, is not


# declaring a function def function-name(parameters): statement(s) #here parameters are optional #code function-name(parameters) #calling a function
Code language: Python (python)


def my_func(): x = 10 print("Value inside function:",x) x = 20 my_func() print("Value outside function:",x)
Code language: PHP (php)


1. List

List is ordered collection of items and can be changed. [] are used to represent lists.


mylist=["iPhone","Pixel","Samsung"] print(mylist[0]) # prints iPhone print(mylist[7]) # throws IndexError : list index out of range print(mylist[-1]) # prints Samsung
Code language: Python (python)


lst.append(val)add an item to list at end
lst.extend(seq)add sequence of items to list at end
lst.insert(index,val)insert an item at given index
lst.remove(val)remove first item with value val
lst.pop([index])→valueremove & return item at index
lst.sort()sort the given list items
lst.reverse()reverse the given list items

2. Tuple

Tuple is ordered collection of items and can’t be changed. () are used to represent Tuples.


myTuple = ["iPhone","Pixel","Samsung"] print(myTuple[0]) # prints iPhone print(myTuple[7]) # throws IndexError: tuple index out of range print(myTuple[-1]) # prints Samsung
Code language: Python (python)

3. Set

Set is unordered collection of items and it is unindexed. {} are used to represent sets.


mySet = {"iPhone", "Pixel", "Samsung"} mySet.add('OnePlus') print(mySet) # prints {'iPhone', 'Samsung', 'OnePlus', 'Pixel'}
Code language: Python (python)


add()to add an element to the setmySet.add(‘value’)
clear()to remove all the elements from the setmySet.clear()
pop()to remove last element from the setmySet.pop()
remove()to remove a specified element from the setmySet.remove(“value”)
del()to delete a setdel myset
copy()to return a copy of the setcopySet = mySet.copy()
union()to return a set containing the union of setsmySet3 = mySet1.union(mySet2)
update()to update the set with the union of this set and othersmySet1.update(mySet2)

4. Dictionary

Dictionary is a collection of key value pairs which is unordered, can be changed, and indexed. They are written in curly brackets with key – value pairs.


mydict = { "brand" :"iPhone", "model": "iPhone 11" } val = mydict["brand"] print(val) # prints iPhone
Code language: Python (python)
d[key]=valueTo add a new key-value pair to dictionary or to change it’s value if key is existing
d.copy()Returns a copy of the dictionary
d.keys()Returns a list containing all the dictionary’s keys
d.values()Returns a list of all the values in the dictionary
d.items()Removes the element with the specified key
d.clear()To empty the dictionary items.
del d[key]To remove an item from a dictionary.
d.pop(key)To remove an item from a dictionary.
d.popitem()To removes the item that was last inserted into the dictionary
d.get(key)Returns the value of the specified key
d.setdefault(key)Returns the value of the specified key. If the key does not exist then returns the default value provided

Conditional Statements

1. If

if conditional-expression : #code
Code language: Python (python)

2. If-else

if conditional-expression : #code else : #code
Code language: Python (python)

3. Nested-If-else

if conditional-expression : #code elif conditional-expression : #code else : #code
Code language: Python (python)


1. For

For loop is used to iterate over arrays(list, tuple, set, dictionary) or strings.


for variable in arrays : #code
Code language: CSS (css)

2. While

while condition #code
Code language: PHP (php)

Useful String Methods

str.replace(“str to be replaced”,”new string to replace”)str.split(“seperator”)len(str)
+ for concatenationstr.count(substr)str.find(substr)
str.index(substr, start, end)str.join(array)str.partition(substr)
str.endswith(value, start, end)str.startswith(value, start, end)str.isspace()

Python with Mongodb

Install a python driver pymongo to connect with MongoDB.

Create Database

import pymongo db = pymongo.MongoClient("mongodb://localhost:27017/") mydb = db["sample"]
Code language: Python (python)

Create collection

import pymongo db = pymongo.MongoClient("mongodb://localhost:27017/") mydb = db["sample"] mycln = mydb["details"]
Code language: Python (python)


<em>#insert a single document</em> doc = mycln.insert_one(mydict) # insert multiple documents mylist =[ {"name": "foo", "age": 20}, {"name": "bar", "age": 25}, {"name": "apple", "age": 30} ] doc1 = mycln.insert_many(mylist)
Code language: Python (python)


#to return all the documents <strong>for</strong> doc <strong>in</strong> mycln.find(): print(doc) # to return first occurence doc1=mycln.find_one() print(doc1)
Code language: Python (python)


# to update a single document mycln.update_one({"name" : "foo"}, {"$set":{"age": 23}})
Code language: Python (python)


# to delete a single document doc1 = mycln.delete_one({"name" : "foo"})
Code language: Python (python)

Python with Files


Use open() function with c or a or w as mode.

file = open("myfile.txt","c")
Code language: Python (python)


Use open() function with r as mode.

file = open("myfile.txt","r") print(
Code language: Python (python)

Update or Append

Use open() function with a or w as mode.

file = open("myfile.txt","a") file.write("Happy learning!!") file.close()
Code language: Python (python)


For deleting files, you must import os module and use os.remove() function.

import os os.remove(filename)
Code language: Python (python)

If you have quires and suggestions put them in the comments.Hope this Python Cheatsheet useful to you, Share & Help Other to learn 🙂

You may also like