Show Menu
Cheatography

Python Ultimate Cheat Sheet (DRAFT) by

This Sheet is Ultimate collection.

This is a draft cheat sheet. It is a work in progress and is not finished yet.

COMMANDS

pip
freeze
>
requir­ments
.
txt
mystr
*
2
's'
in
mystr

STRING METHODS

str
.
upper()
String to uppercase
str
.
lower()
String to lowercase
str
.
count('t')
Occurr­ences of element
str
.
strip()
Strip whites­paces
str
.
endswith()
Returns True if
str
.
index()
Position of first occurrence
str
.
isdigit()
Returns True if all are digits

SLICING

list
[
Initial
:
End
:
IndexJump
]
my_list
[1:3]
Select items at index 1 and 2
my_list
[1:]
Select items after index 0
my_list
[:3]
Select items before index 3
my_list
[:]
  Copy my_list
 

LISTS

nums
=
[2,3,4,5]
nums
.
append(6)
Adds 6 to the end
insert(
0,6)
Adds 6 at index position of 0
nums
.
remove(6)
Removes 6
nums
.
pop()
Removes the last item
nums
.
clear()
Removes all the items
nums
.
index(8)
Returns the index of first 8
nums
.
sort()
Sorts the list
nums
.
reverse()
Reverses the list
nums
.
copy()
Returns a copy of the list
del
lis[2:5]
Deletes elements in range
nums
.
extend(b)
Extend existing list with list
b

ADVANCE LISTS

Removing duplicates
Use
dict
.
fromkeys()
function to convert list into dictionary with list elements as keys. Then convert the dictionary back to list.

list
=
[‘a’, ’b’, ’c’, ’b’, ’a’]

list_2
=
list
(
dict
.
fromkeys
(
list
))

Filtering a list
list
=
[item for item in m_list if item > 20]

Combining lists
Each item from list A is combined with corres­ponding elements from list B in the form of a tuple.
comb_list
=
list
(
zip
(
list_1, list_2
))

Finding the most common item
list
=
['a','­a',­'a'­,'d­','­d','e']

frequent
=
max
(
set
(list),
key=
list
.
count)

Flatten a list of lists
compre­hen­sion-to convert a list of lists into single list.
list=
[item
for
List
in
listOflist
for
item
in
List
]
 

PYTHON

this is it if than.
are you serious?

RANGE

range
(5)
Returns sequence from 0 to 4
range
(2000,
2018)
Returns a sequence form 2000 to 2017
range
(0,11,2)
Returns seq. from 0 to 10 with increment of 2
range
(0,-10,-1)
Returns a sequence from 0 to -9
list
(range
(5))
Returns a list from 0 to 4