Show Menu
Cheatography

Python Data Structures Cheat Sheet by

Python Data Structures

Python Data Structures (Lavanya.R - 2247249)

The basic Python data structures in Python include list, set, tuples, and dictio­nary. Each of the data structures is unique in its own way. Data structures are “conta­iners” that organize and group data according to type.

Lists

A list is a data structure in Python that is a mutable, or change­able, ordered sequence of elements.

Access Items (Same for tuples)

Print the second item of the list:
print(­thi­sli­st[1])
Print the last item of the list:
print(­thi­sli­st[-1])
A range of indexes by specifying where to start and where to end the range.
print(­thi­sli­st[­2:5])
Returns the items from the beginning to, but NOT including, "­kiw­i"
print(­thi­sli­st[:4])
Returns the items from "­che­rry­" to the end
print(­thi­sli­st[2:])
Returns the items from "­ora­nge­" (-4) to, but NOT including "­man­go" (-1)
print(­thi­sli­st[­-4:-1])
Check if "­app­le" is present in the list
if "­app­le" in thislist: print(­"Yes, 'apple' is in the fruits list")
thislist = ["ap­ple­", "­ban­ana­", "­che­rry­", "­ora­nge­", "­kiw­i", "­mel­on", "­man­go"]

List Methods

append()
Adds an element at the end of the list
list.a­ppend (element)
clear()
Removes all the elements from the list
list.c­lear()
copy()
Returns a copy of the list
list.c­opy()
count()
Returns the number of elements with the specified value
List.c­oun­t(e­lement)
extend()
Add the elements of a list (or any iterable), to the end of the current list
List1.e­xt­end­(List2)
index()
Returns the index of the first element with the specified value
List.i­nde­x(e­lem­ent­[,s­tar­t[,­end]])
insert()
Adds an element at the specified position
list.i­nse­rt(­<po­sition, element)
pop()
Removes the element at the specified position
list.p­op(­[in­dex])
remove()
Removes the first item with the specified value
list.r­emo­ve(­ele­ment)
reverse()
Reverses the order of the list
list_n­ame.re­verse()
sort()
Sorts the list
List_n­ame.sort()
del()
Element to be deleted is mentioned using list name and index.
del list.[­index]

List Compre­hension

Containing only the fruits with the letter "­a" in the name.
newlist = [x for x in fruits if "­a" in x]
Only accept items that are not "­app­le":
newlist = [x for x in fruits if x != "­app­le"]
Accept only numbers lower than 5:
newlist = [x for x in range(10) if x < 5]
Set the values in the new list to upper case:
newlist = [x.upper() for x in fruits]
Set all values in the new list to 'hello':
newlist = ['hello' for x in fruits]
Return "­ora­nge­" instead of "­ban­ana­":
newlist = [x if x != "­ban­ana­" else "­ora­nge­" for x in fruits]
List compre­hension offers a shorter syntax when you want to create a new list based on the values of an existing list.

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(­new­list)

The Syntax
newlist = [expre­ssion for item in iterable if condition == True]
The return value is a new list, leaving the old list unchanged.

Tuples

A tuple is a collection of objects which ordered and immutable. The differ­ences between tuples and lists are, the tuples cannot be changed unlike lists and tuples use parent­heses, whereas lists use square brackets.

Add Items

Since tuples are immutable, they do not have a build-in append() method, but there are other ways to add items to a tuple.

Convert the tuple into a list, add "­ora­nge­", and convert it back into a tuple:
thistuple = ("ap­ple­", "­ban­ana­", "­che­rry­")
y = list(t­his­tuple)
y.appe­nd(­"­ora­nge­")
thistuple = tuple(y)
 

Add tuple to a tuple.

You are allowed to add tuples to tuples, so if you want to add one item, (or many), create a new tuple with the item(s), and add it to the existing tuple

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(­thi­stuple)

Access Items

You cannot access items in a set by referring to an index or a key.

But you can loop through the set items using a for loop, or ask if a specified value is present in a set, by using the in keyword.

thisset = {"ap­ple­", "­ban­ana­", "­che­rry­"}

for x in thisset:
print(x)
Once a set is created, you cannot change its items, but you can add new items.

Tuple Methods

count()
Returns the number of times a specified value occurs in a tuple
index()
Searches the tuple for a specified value and returns the position of where it was found

Remove Items

Convert the tuple into a list, remove "­app­le", and convert it back into a tuple:

thistuple = ("ap­ple­", "­ban­ana­", "­che­rry­")
y = list(t­his­tuple)
y.remo­ve(­"­app­le")
thistuple = tuple(y)
The del keyword can delete the tuple comple­tely:

thistuple = ("ap­ple­", "­ban­ana­", "­che­rry­")
del thistuple
print(­thi­stuple) #this will raise an error because the tuple no longer exists

Change Tuple Values

Once a tuple is created, you cannot change its values. Tuples are unchan­geable, or immutable as it also is called.

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)

Sets

A Set is an unordered collection data type that is iterable, mutable and has no duplicate elements.
Set is define in { }

Add Items

To add one item to a set use the add() method.

Example
Add an item to a set, using the add() method:

thisset = {"ap­ple­", "­ban­ana­", "­che­rry­"}
thisse­t.a­dd(­"­ora­nge­")
print(­thi­sset)
To add items from another set into the current set, use the update() method.

Example
Add elements from tropical into thisset:

thisset = {"ap­ple­", "­ban­ana­", "­che­rry­"}
tropical = {"pi­nea­ppl­e", "­man­go", "­pap­aya­"}
thisse­t.u­pda­te(­tro­pical)
print(­thi­sset)

The object in the update() method does not have to be a set, it can be any iterable object (tuples, lists, dictio­naries etc.).

Remove Set Items

remove()
thisse­t.r­emo­ve(­"­ban­ana­")
discard()
thisse­t.d­isc­ard­("ba­nan­a")
clear()
method empties the set
del keyword
will delete the set comple­tel­y(del thisset)
We can also use the pop() method to remove an item, but this method will remove the last item. Remember that sets are unordered, so you will not know what item that gets removed.

The return value of the pop() method is the removed item.

thisset = {"ap­ple­", "­ban­ana­", "­che­rry­"}
x = thisse­t.pop()
print(x)
print(­thi­sset)
 

Set Methods

add()
Adds an element to the set
clear()
Removes all the elements from the set
copy()
Returns a copy of the set
differ­ence()
Returns a set containing the difference between two or more sets
differ­enc­e_u­pdate()
Removes the items in this set that are also included in another, specified set
discard()
Remove the specified item
inters­ect­ion()
Returns a set, that is the inters­ection of two other sets
inters­ect­ion­_up­date()
Removes the items in this set that are not present in other, specified set(s)
isdisj­oint()
Returns whether two sets have a inters­ection or not
issubset()
Returns whether another set contains this set or not
issupe­rset()
Returns whether this set contains another set or not
pop()
Removes an element from the set
remove()
Removes the specified element
symmet­ric­_di­ffe­rence()
Returns a set with the symmetric differ­ences of two sets
symmet­ric­_di­ffe­ren­ce_­upd­ate()
inserts the symmetric differ­ences from this set and another
union()
Return a set containing the union of sets
update()
Update the set with the union of this set and others

Dictionary

Dictionary in Python is a collection of keys values, used to store data values like a map, which, unlike other data types which hold only a single value as an element.

Adding Items in Dictionary

Adding an item to the dictionary is done by using a new index key and assigning a value to it:

Example
thisdict = {
"­bra­nd": "­For­d",
"­mod­el": "­Mus­tan­g",
"­yea­r": 1964
}
thisdi­ct[­"­col­or"] = "­red­"
print(­thi­sdict)
The update() method will update the dictionary with the items from a given argument. If the item does not exist, the item will be added.

The argument must be a dictio­nary, or an iterable object with key:value pairs.

Example
Add a color item to the dictionary by using the update() method:

thisdict = {
"­bra­nd": "­For­d",
"­mod­el": "­Mus­tan­g",
"­yea­r": 1964
}
thisdi­ct.u­pd­ate­({"c­olo­r": "­red­"})

Removing Items in Dictionary

The pop() method removes the item with the specified key name:
thisdi­ct.p­op­("mo­del­")
The popitem() method removes the last inserted item
thisdi­ct.p­op­item()
The del keyword removes the item with the specified key name:
del thisdi­ct[­"­mod­el"]
The del keyword can also delete the dictionary comple­tely:
del thisdict
The clear() method empties the dictionary
thisdi­ct.c­lear()
thisdict = {
"­bra­nd": "­For­d",
"­mod­el": "­Mus­tan­g",
"­yea­r": 1964
}

Dictionary Methods

clear()
Removes all the elements from the dictionary
dictio­nar­y.c­lear()
copy()
Returns a copy of the dictionary
dictio­nar­y.c­opy()
fromkeys()
Returns a dictionary with the specified keys and value
dict.f­rom­key­s(keys, value)
get()
Returns the value of the specified key
dictio­nar­y.g­et(­key­name, value)
items()
Returns a list containing a tuple for each key value pair
dictio­nar­y.i­tems()
keys()
Returns a list containing the dictio­nary's keys
dictio­nar­y.k­eys()
pop()
Removes the element with the specified key
dictio­nar­y.p­op(­key­name, defaul­tvalue)
popitem()
Removes the last inserted key-value pair
dictio­nar­y.p­opi­tem()
setdef­ault()
Returns the value of the specified key. If the key does not exist: insert the key, with the specified value
dictio­nar­y.s­etd­efa­ult­(ke­yname, value)
update()
Updates the dictionary with the specified key-value pairs
dictio­nar­y.u­pda­te(­ite­rable)
values()
Returns a list of all the values in the dictionary
dictio­nar­y.v­alues()

Python Modules

Import our program as python module

-> Create file in notepad using .py extension
-> Upload it in sample data
-> Copy path of the uploaded file
Code:
from google.colab import files
!cp path /content
       
 

Comments

No comments yet. Add yours below!

Add a Comment

Your Comment

Please enter your name.

    Please enter your email address

      Please enter your Comment.