Show Menu
Cheatography

Python List, dictionaries, tuple, string methods Cheat Sheet (DRAFT) by

Here is the Python topics cheat sheet

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

Python Lists

List
To Create a List:
thislist = ["ap­ple­", "­ban­ana­", "­che­rry­"]
print(­thi­slist)

output::
['apple', 'banana', 'cherry']
A list can contain different data types::
Example::
list1 = ["ab­c", 34, True, 40, "­mal­e"]
What is the data type of a list?
mylist = ["ap­ple­", "­ban­ana­", "­che­rry­"]
print(­typ­e(m­ylist))

output:: <class 'list'>
List items can be accessed by referring to the index number:
thislist = ["ap­ple­", "­ban­ana­", "­che­rry­"]
print(­thi­sli­st[1])

output:: banana
To change the value of a specific item, refer to the index number:
thislist = ["ap­ple­", "­ban­ana­", "­che­rry­"]
thisli­st[1] = "blackcurrant"
print(­thi­slist)

output:: ['apple', 'black­cur­rant', 'cherry']
To add an item to the end of the list, use the append() method:
thislist = ["ap­ple­", "­ban­ana­", "­che­rry­"]
thisli­st.a­pp­end­("or­ang­e")
print(­thi­slist)

output:: ['apple', 'banana', 'cherry', 'orange']
To append elements from another list to the current list, use the extend() method.
list_A = ["ap­ple­", "­ban­ana­", "­che­rry­"]
list_B = ["ma­ngo­", "­pin­eap­ple­", "­pap­aya­"]
list_A.ex­ten­d(l­ist_B)
print(­list_A)

output::
['apple', 'banana', 'cherry', 'mango', 'pinea­pple', 'papaya']
The remove() method removes the specified item.
list_A = ["ap­ple­", "­ban­ana­", "­che­rry­"]
list_A.remove("banana")
print(list_A)

output:: ['apple', 'cherry']
The pop() method removes the specified index
with out idex it will remove last item
list_A = ["ap­ple­", "­ban­ana­", "cherry"]
list_A.pop(1)
print(list_A)

output:: ['apple', 'cherry']
The **del keyword removes the specified index
Also delete the list completely
thislist = ["ap­ple­", "­ban­ana­", "­che­rry­"]
del thisli­st[0]
print(thislist)

output::['banana', 'cherry']
The clear() method empties the list.
thislist = ["ap­ple­", "­ban­ana­", "­che­rry­"]
thislist.clear()
print(thislist)

output::[]
loop through the list items by using a for loop:
thislist = ["ap­ple­", "­ban­ana­", "­che­rry­"]
for x in thislist:
print(x)

output::
apple
banana
cherry
loop through the list items by referring to their index number.
Use the range() and len() functions to create a suitable iterable.
thislist = ["ap­ple­", "­ban­ana­", "­che­rry­"]
for i in range(­len­(th­isl­ist)):
print(thislist[i])

output::
apple
banana
cherry
loop through the list items by using a while loop.
thislist = ["ap­ple­", "­ban­ana­", "­che­rry­"]
i = 0
while i < len(th­isl­ist):
print(thislist[i]) i = i + 1

output ::
apple
banana
cherry
List Compre­hension offers the shortest syntax for looping through lists:
thislist = ["ap­ple­", "­ban­ana­", "­che­rry­"]
[print(x) for x in thislist]

output::
apple
banana
cherry
List compre­hension offers a shorter syntax
when you want to create a new list
based on the values of an existing list.
Without list compre­hension
fruits = ["ap­ple­", "­ban­ana­", "­che­rry­", "­kiw­i", "­man­go"]
newlist = []
for x in fruits:
if "­a" in x:
newlis­t.a­ppe­nd(x)
print(newlist)
With list compre­hension you can do
all that with only one line of code
fruits = ["ap­ple­", "­ban­ana­", "­che­rry­", "­kiw­i", "­man­go"]
newlist = [x for x in fruits if "­a" in x]
print(newlist)
sort() method that will sort the list alphan­ume­ric­ally, ascending, by default:
thislist = ["or­ang­e", "­man­go", "­kiw­i", "­pin­eap­ple­", "­ban­ana­"]
thislist.sort()
print(thislist)

output::
['banana', 'kiwi', 'mango', 'orange', 'pinea­pple']
To make a copy, one way is to use the built-in List method copy().
thislist = ["ap­ple­", "­ban­ana­", "­che­rry­"]
mylist = thisli­st.c­opy()
print(mylist)
output::['apple', 'banana', 'cherry']
List count() Method
Return the number of times the value "­che­rry­"
appears in the fruits list:
fruits = ['apple', 'banana', 'cherry']
x = fruits.co­unt­("ch­err­y")

output::
1
There are some list methods that will change the order, but in general: the order of the items will not change.
 

Dictio­naries in Python

Dictio­naries are used to store data values in key:value pairs.
It is a collection which is ordered*, changeable and do not allow duplic­ates.
Create and print a dictio­nary:
thisdict = { "­bra­nd": "­For­d", "­mod­el": "­Mus­tan­g", "­yea­r": 1964 }
print(thisdict)


output
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964}
You can access the items of a dictionary by referring to
its key name, inside square brackets:
thisdict = { "­bra­nd": "­For­d", "­mod­el": "­Mus­tan­g", "­yea­r": 1964 }
x = thisdi­ct[­"­mod­el"]
print(x)

output::Mustang
The keys() method will return a list of all the keys in the dictio­nary.
thisdict = { "­bra­nd": "­For­d", "­mod­el": "­Mus­tan­g", "­yea­r": 1964 }
x = thisdi­ct.k­eys()
print(x)

output:: dict_k­eys­(['­brand', 'model', 'year'])
The values() method will return a list of all the values in the dictio­nary.
thisdict = { "­bra­nd": "­For­d", "­mod­el": "­Mus­tan­g", "­yea­r": 1964 }
x = thisdi­ct.v­al­ues()
print(x)

output::dict_v­alu­es(­['F­ord', 'Mustang', 1964])
we can change the value of a specific item by referring to its key name:
thisdict = { "­bra­nd": "­For­d", "­mod­el": "­Mus­tan­g", "­yea­r": 1964 }
thisdict["year"] = 2018
print(thisdict)

output::{'brand': 'Ford', 'model': 'Mustang', 'year': 2018}
The update() method will update the dictionary with
the items from the given argument.
thisdict = { "­bra­nd": "­For­d", "­mod­el": "­Mus­tan­g", "­yea­r": 1964 }
thisdict.update({"year": 2020})
print(thisdict)

output::{'brand': 'Ford', 'model': 'Mustang', 'year': 2020}
Adding an item to the dictionary is done
by using a new index key and assigning a value to it:
thisdict = {"br­and­": "­For­d", "­mod­el": "­Mus­tan­g", "­yea­r": 1964 }
thisdict["color"] = "­red­"
print(thisdict)

output::
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964, 'color': 'red'}
You can loop through a dictionary by using a for loop.
thisdict = { "­bra­nd": "­For­d", "­mod­el": "­Mus­tan­g", "­yea­r": 1964 }
for x in thisdict:
print(x)

output::
brand
model
year
Make a copy of a dictionary with the copy() method:
thisdict = { "­bra­nd": "­For­d", "­mod­el": "­Mus­tan­g", "­yea­r": 1964 }
mydict = thisdi­ct.c­opy()
print(mydict)

output:: {'brand': 'Ford', 'model': 'Mustang', 'year': 1964}
A dictionary can contain dictio­naries, this is called nested dictio­naries.
myfamily = {
"­chi­ld1­" : {
"name" : "­Emi­l",
"year" : 2004
},
"child2" : {
"name" : "­Tob­ias­",
"year" : 2007
},
"child3" : {
"name" : "­Lin­us",
"year" : 2011
}
}
print(myfamily)

output::
{'child1': {'name': 'Emil', 'year': 2004},
'child2': {'name': 'Tobias', 'year': 2007},
'child3': {'name': 'Linus', 'year': 2011}}
To access items from a nested dictionary,
you use the name of the dictio­naries,
starting with the outer dictio­nary:
myfamily = {
"child1" : {
"name" : "­Emi­l",
"year" : 2004
},
"child2" : {
"name" : "­Tob­ias­",
"year" : 2007
},
"child3" : {
"name" : "­Lin­us",
"year" : 2011
}
}
print(myfamily["child2"]["name"])

output::Tobias
setdef­ault() Method
car = {
"brand": "­For­d",
"model": "­Mus­tan­g",
"year": 1964
}
x = car.se­tde­fau­lt(­"­mod­el", "­Bro­nco­")
print(x)

output:: Mustang
As of Python version 3.7, dictio­naries are ordered. In Python 3.6 and earlier, dictio­naries are unordered.

Python Strings

Strings
Strings in python are surrounded by either single quotation marks,
or double quotation marks.
Example::
print(­"­Hel­lo")
print('Hello')

output::
Hello
Hello
Assign String to a Variable

Example::
a = "­Hel­lo"
print(a)

output:: {nl}} Hello
Multiline Strings
Example::
a = "­"­"­Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt {nl}} ut labore et dolore magna aliqua."""
print(a)

output::
Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua.
Strings are Arrays
Example::
Get the character at position 1 (remember that the first character has the position 0):
a = "­Hello, World!­"
print(a[1])
{nl}}o­utput::
e
Looping Through a String
Example::
for x in "­ban­ana­":
print(x)

output:: {nl}}o­utput::
**b
a
n
a
n
a
String Length
The len() function returns the length of a string:
Example::
a = "­Hello, World!­"
print(len(a))

output::
13
Check String
Example::
txt = "The best things in life are free!"
print("free" in txt)

output:: {nl}}True
Use it in an if statement:
Example::
txt = "The best things in life are free!"
if "­fre­e" in txt:
print("Yes, 'free' is presen­t.")
{nl}}o­utput::
Yes, 'free' is present.
Check if NOT
Example::
txt = "The best things in life are free!"
print("expensive" not in txt)

output:: {nl}}True
using 'if'
Example::
txt = "The best things in life are free!"
if "­exp­ens­ive­" not in txt:
print("No, 'expen­sive' is NOT presen­t.")
{nl}}o­utput::
No, 'expen­sive' is NOT present.
Slicing
Example::
b = "­Hello, World!­"
print(b[2:5])

output::
llo
Modify Strings to Upper Case
Example::
a = "­Hello, World!­"
print(a.upper())

output::
HELLO, WORLD!
Modify Strings to Lower Case
Example::
a = "­Hello, World!­"
print(a.lower())

output::
hello, world!
Remove Whitespace
The strip() method removes any whitespace from the beginning or the end:
Example::
a = " Hello, World! "
print(a.strip())

output::
Hello, World!
Replace String
Example::
a = "­Hello, World!­"
print(a.replace("H", "­J"))

output::
Jello, World!
Split String
Example::
a = "­Hello, World!­"
b = a.spli­t(",­")
print(b)

output::
['Hello', ' World!']
String Concat­enation
Example::
a = "­Hel­lo"
b = "­Wor­ld"
c = a + b
print(c)

output::
HelloWorld
To add a space between them, add a " ":
Example::
a = "­Hel­lo"
b = "­Wor­ld"
c = a + " " + b
print(c)

output::
Hello World
Format - Strings
Use the format() method to insert numbers into strings:
Example::
age = 30
txt = "My name is Srinivas, and I am {}"
print(txt.format(age))

output::
My name is Srinivas, and I am 30
You can use index numbers {0} to be sure the
arguments are placed in the correct placeh­olders:
Example::
quantity = 3
itemno = 567
price = 49.95
myorder = "I want to pay {2} dollars for {0} pieces of item {1}."
print(myorder.format(quantity, itemno, price))

output::
I want to pay 49.95 dollars for 3 pieces of item 567
Escape Characters
The escape character allows you to use double quotes
when you normally would not be allowed:
Example::
txt = "Iam \"Im­por­tan­t\" in this line."
print(txt)

output::
Iam "­Imp­ort­ant­" in this line
Capita­lize() Method In Strings
The first character is converted to upper case, and
the rest are converted to lower case:
Example::
txt = "­python is FUN!"
x = txt.ca­pit­alize()
print (x)

output::
Python is fun!
String count() Method
Return the number of times the value "­app­le" appears in the string:
Example::
txt = "I love apples, apple are my favorite fruit"
x = txt.co­unt­("ap­ple­")
print(x)

output::
2
String endswith() Method
Example::
txt = "­Hello, welcome to my world."­
x = txt.en­dsw­ith­(".")
print(x)

output::
True
String find() Method
Example::
txt = "­Hello, welcome to my world."­
x = txt.fi­nd(­"­wel­com­e")
print(x)

output::
7
String isalnum() Method
Example::
txt = "­Com­pan­y12­"
x = txt.is­alnum()
print(x)

output::
True
String isalpha() Method
Example::
txt = "­Com­pan­yX"
x = txt.is­alpha()
print(x)

output::
True
Strings in python are surrounded by either single quotation marks, or double quotation marks.
 

Tuples In Python

Tuple:

Tuples are used to store multiple items in a single variable.
A tuple is a collection which is ordered and unchan­geable.
Tuples are written with round brackets.
Example::
thistuple = ("ap­ple­", "­ban­ana­", "­che­rry­")
print(thistuple).

output::('apple', 'banana', 'cherry')
Tuple Items
Tuple items are ordered, unchan­geable, and allow duplicate values.
Tuple items are indexed, the first item has index [0],
the second item has index [1] etc.
Ordered
When we say that tuples are ordered,
it means that the items have a defined order,
and that order will not change.
Unchan­geable
Tuples are unchan­geable, meaning that we cannot change,
add or remove items after the tuple has been created.
Allow Duplicates
Example::
thistuple = ("ap­ple­", "­ban­ana­", "­che­rry­", "­app­le", "­che­rry­")
print(thistuple)

output::
('apple', 'banana', 'cherry', 'apple', 'cherry')
Create Tuple With One Item
To create a tuple with only one item,
you have to add a comma after the item,
otherwise Python will not recognize it as a tuple.
thistuple = ("ap­ple­",)
print(type(thistuple))
#NOT a tuple
thistuple = ("ap­ple­")
print(type(thistuple))
output::
<class 'tuple­'>
<class 'str'>
Access Tuple Items
Print the second item in the tuple:
thistuple = ("ap­ple­", "­ban­ana­", "­che­rry­")
print(thistuple[1])
output::
banana
Change Tuple Values
Once a tuple is created, you cannot change its values as they are called immutable.
But there is a workar­ound. You can convert the tuple into a list,
change the list, and convert the list back into a tuple.
x = ("ap­ple­", "­ban­ana­", "­che­rry­")
y = list(x)
y[1] = "­kiw­i"
x = tuple(y)
print(x)

output::
("ap­ple­", "­kiw­i", "­che­rry­")
Add tuple to a tuple.
Example::
Create a new tuple with the value "­ora­nge­", and add that tuple:
thistuple = ("ap­ple­", "­ban­ana­", "­che­rry­")
y = ("or­ang­e",)
thistuple += y
print(thistuple)

output::
('apple', 'banana', 'cherry', 'orange')
Unpacking a Tuple
When we create a tuple, we normally assign values to it.
This is called "­pac­kin­g" a tuple:
Packing a tuple:
fruits = ("ap­ple­", "­ban­ana­", "­che­rry­")
print(fruits)

output::
('apple', 'banana', 'cherry')
But, in Python, we are also allowed to extract the values back into variables.
This is called "unpacking":
unpack Tuple
fruits = ("ap­ple­", "­ban­ana­", "­che­rry­")
(green, yellow, red) = fruits
print(green)
print(yellow)
print(red)

output::
apple
banana
cherry
Using Asterisk*
If the number of variables is less than the number of values,
you can add an * to the variable name and the values
will be assigned to the variable as a list:

Example::
fruits = ("ap­ple­", "­ban­ana­", "­che­rry­", "­str­awb­err­y", "­ras­pbe­rry­")
(green, yellow, *red) = fruits
print(­green)
print(yellow)
print(red)

output::
apple
banana
['cherry', 'straw­berry', 'raspb­erry']
Loop Through a Tuple
You can loop through the tuple items by using a for loop.
Example::
thistuple = ("ap­ple­", "­ban­ana­", "­che­rry­")
for x in thistuple:
print(x)

output::
apple
banana
cherry
Loop Through the Index Numbers In Tuples
Use the range() and len() functions to create a suitable iterable.
Example::
thistuple = ("ap­ple­", "­ban­ana­", "­che­rry­")
for i in range(­len­(th­ist­uple)):
print(­thi­stu­ple[i])

output::
apple
banana
cherry
Using a While Loop In Tuples

Example::
thistuple = ("ap­ple­", "­ban­ana­", "­che­rry­")
i = 0
while i < len(th­ist­uple):
print(­thi­stu­ple[i])
i = i + 1

output::
apple
banana
cherry
Join Two Tuples
To join two or more tuples you can use the + operator:
Example::
tuple1 = ("a", "­b" , "­c")
tuple2 = (1, 2, 3)
tuple3 = tuple1 + tuple2
print(­tuple3)

output::
('a', 'b', 'c', 1, 2, 3)
Multiply Tuples
Example::
fruits = ("ap­ple­", "­ban­ana­", "­che­rry­")
mytuple = fruits * 2
print(­myt­uple)

output::
('apple', 'banana', 'cherry', 'apple', 'banana', 'cherry')
Tuple count() Method

Example::
thistuple = (1, 3, 7, 8, 7, 5, 4, 6, 8, 5)
x = thistu­ple.co­unt(5)
print(x)

output::
2
Tuple index() Method
Example::
thistuple = (1, 3, 7, 8, 7, 5, 4, 6, 8, 5)
x = thistu­ple.in­dex(8)
print(x)

output::
3
When creating a tuple with only one item, remember to include a comma after the item, otherwise it will not be identified as a tuple.