Chapter 2
Data Structures in
Contents: Lists Tuples Sets Dictionary Arrays
(c) Bharadwaj V Dept of ECE NUS (2023) 1
Types of storage structures
• Python data structures to store & process data!
Lists Tuples Sets Dictionaries Arrays
Each of the above comes with certain built-in
methods which we can use while processing. For
instance, we may need to do sorting, adding
another element to a list, removing an element
from a list, etc. All these can be done using built-in
methods!
(c) Bharadwaj V Dept of ECE NUS (2023) 2
Python - List
• List creation:
>>> mylist = [] // open and close square brackets; Empty list
>>> yourlist = [1, 2, 4, 5, 3, 3, 3, 6]
• Accessing a list: Index 0 – first elem. (as in the strings)
>>> print(yourlist[0], yourlist[3]) Output: >> 1, 5
• Adding an element to a list:
>>> mylist.append(0) #adds 0 as the first element to
mylist (which is an empty list) ; append() is a method!
Note: List can be sliced too! Same rules as we learnt for strings!
Try it out! (c) Bharadwaj V Dept of ECE NUS (2023) 3
Python - List methods
(Note: This is not an exhaustive list)
FUNCTION DESCRIPTION
append() Add an element to the end of the list
extend() Add all elements of a list to the another list
insert() Insert an item at the defined index
remove() Removes an item from the list
pop() Removes and returns an element at the given index
clear() Removes all items from the list
index() Returns the index of the first matched item
count() Returns the count of number of items passed as an argument
sort() Sort items in a list in ascending order
reverse() Reverse the order of items in the list
copy() Returns a copy of the list
len() Returns the length of the list (# of elements in the list)
Create an empty list and demonstrate some of the
Tutorial 2.1 above methods; Observe how elements are accessed!
(c) Bharadwaj V Dept of ECE NUS (2023) 4
Python – Tuples
Tuples are immutable and can contain any number of elements
and of any datatype (like strings, integers, list, etc.).
Tuples are created by placing sequence of values separated by
‘comma’ with or without the use of parentheses for grouping of
data sequence.
Single element tuple: Tuples can also be created with a single
element, but it is a bit tricky. Having one element in the
parentheses is not sufficient, there must be a trailing ‘comma’ to
make it a tuple.
(c) Bharadwaj V Dept of ECE NUS (2023) 5
Python – Tuples
Try to create, print and see the following! Self-learning
>>> mytup1 = () Tutorial 2.2
>>> mytup1 = (‘abba’,’baba’)
>>> mytup2 = (1,2,3)
>>> mytup3 = (mytup1,mytup2)
>>> mytup4 = mytup2*3 //tuple via repetition
>>> mytup5 = (‘hello’,)*2 // single tuple observe a comma
>>> mytup6 = mytup4 + mytup5 // Concatenation
>>> del mytup6 // deleting a tuple
You can try slicing a tuple! Same as strings and lists
(c) Bharadwaj V Dept of ECE NUS (2023) 6
Python – Tuples
(Note: This is not an exhaustive list)
Method Description
count() returns occurrences of element in a tuple
index() returns smallest index of element in tuple
len() returns Length of an Object
max() returns largest element
min() returns smallest element
reversed() returns reversed iterator of a sequence
slice() creates a slice object specified by range()
sum() Add items of an iterable
tuple() Creates a Tuple
Tutorial 2.3 Create an empty tuple and demonstrate some of the
DIY (follow above methods
Tutorial 2.2 style) (c) Bharadwaj V Dept of ECE NUS (2023) 7
Know your data structures correctly! - List vs
tuples
>>> a = ["apples", Let us attempt the above using
tuples:
"bananas", "oranges”]
Let us try to change >>> a = ("apples", "bananas",
element 0: "oranges")
>>> a[0] = "berries”
>>> a[0] = "berries"
>>> a Traceback (most recent call last):
['berries', 'bananas', 'oranges’] File "", line 1, in
TypeError: 'tuple' object does not
support item assignment
Why? List: Mutable entity;
Tuple: Immutable entity
(c) Bharadwaj V Dept of ECE NUS (2023) 8
Python – Sets
A set is a collection which is unordered and
unindexed. In Python, sets are written with curly
brackets.
>>> myset = set() #method to create an empty set
>>> myset = {”Apple", “Banana", “Orange"}
>>>print(myset)
Check if any element is in this set.
>>> ‘Banana’ in myset
True
Note: You can perform all Set operations!
(c) Bharadwaj V Dept of ECE NUS (2023) 9
Python – Sets
(Note: This is not an exhaustive list)
Method Description
add() Adds an element to the set
clear() Removes all the elements from the set
copy() Returns a copy of the set
difference() Returns a set containing the difference between two or more
sets
discard() Remove the specified item
intersection() Returns a set, that is the intersection of two other sets
isdisjoint() Returns whether two sets have a intersection or not
issubset() Returns whether another set contains this set or not
issuperset() Returns whether this set contains another set or not
pop() Removes an element from the set
remove() Removes the specified element
union() Return a set containing the union of sets
update() Update the set with the union of this set and others
(c) Bharadwaj V Dept of ECE NUS (2023) 10
Python – Sets
Tutorial 2.4
Create an empty set and demonstrate some of the
above methods
Remarks:
Some differences between Sets and Lists
• Sets cannot contain duplicates
• Sets are unordered (when you print they display in order)
• Sets can contain only hashable items (later!)
• In practical applications, lists are very nice to sort and
have order while sets are nice to use when you don't
want duplicates and don't care about order.
(c) Bharadwaj V Dept of ECE NUS (2023) 11
Python – Dictionary
A dictionary is a collection which is unordered, mutable and
indexed. In Python, dictionaries are written with curly
brackets, and they have keys & values.
So, you can search/locate an item using a key! Try the
following! Key : Value is the format followed.
mydict = {
"brand": ”Sony", // key : value
"model": ”Sq12345Z",
"year": 2019
}
item = mydict["model"]
print(item)
(c) Bharadwaj V Dept of ECE NUS (2023) 12
Python – Dictionary
Try the following! Tutorial: 2.5
Change the value of a specific item by referring to its key name:
>>> mydict[‘model’] = ‘SQ12345AZ’ # dictionaries are mutable
>>> print(mydict)
Add a new item item using a new index key and assigning a
value to it:
>>> mydict[‘color’] = ‘Black’
>>> print(mydict)
Remove an item - pop() method removes the item with the
specified key name:
>>> mydict.pop(“model”)
>>> print(mydict)
(c) Bharadwaj V Dept of ECE NUS (2023) 13
Python – Dictionary (Note: This is not an exhaustive list)
Method Description
clear() Removes all the elements from the dictionary
copy() Returns a copy of the dictionary
fromkeys() Returns a dictionary with the specified keys and values
get() Returns the value of the specified key
items() Returns a list containing a tuple for each key value pair
keys() Returns a list containing the dictionary's keys
pop() Removes the element with the specified key
popitem() Removes the last inserted key-value pair
update() Updates the dictionary with the specified key-value pairs
values() Returns a list of all the values in the dictionary
(c) Bharadwaj V Dept of ECE NUS (2023) 14
Python – Arrays
Arrays are handled in python by a module named “array“. If you
want to manipulate only a specific data type values, then use
arrays.
How do I create an array? array(data type, list) - This function
is used to create an array with data type and value list specified
as its arguments. (Ex: myarr = array.array(‘b’,[1,2,3,4])
We need to specify the data type explicitly. Some useful data
types and representations are given in the table (see next slide)
Note: You need to import array to avail all methods that can be
used for array processing!
>> import array (c) Bharadwaj V Dept of ECE NUS (2023) 15
Python – Arrays
Type Description Data Number of bytes
Code Type used to store
‘b’ signed char int 1
‘B’ unsigned char int 1
‘h’ signed short int 2
‘H’ unsigned short int 2
‘i’ signed int int 2
‘I’ unsigned int int 2
‘l’ signed long int 4
‘L’ unsigned long int 4
‘q’ signed long long int 8
‘Q’ unsigned long long int 8
‘f’ float float 4
‘d’ double float 8
‘u’ Py_UNICODE unicode char 2
(c) Bharadwaj V Dept of ECE NUS (2023) 16
Python – Arrays
Array elements are accessed using the same
convention you learnt with lists!
Some useful array methods include:
append() insert() pop() reverse()
remove() index() count() extend() … and more
Tutorial 2.6
Create an array of integers and demonstrate some of the
above methods; Observe how elements are accessed!
(c) Bharadwaj V Dept of ECE NUS (2023) 17
2D arrays
• Each row needs to be specified separately as a list! In
this type of array the position of a data element is
referred to by two indices instead of one. So it
represents a table with rows and columns of data.
Example:
>>> from array import *
>>> arr = [[1, 10, 0, 2], [15, 4,5], [7, 8, 0, 3], [2,11,8,6]]
Try printing a few elements!
>>> print (arr) # entire array
>>> print (arr[0]) # 1st row
>>> print (arr[0][2]) # 1st row 2nd elem
>>> print (arr[3]) # 3rd row
>>> print (arr[2][4]) # what will you see?
(c) Bharadwaj V Dept of ECE NUS (2023) 18
Final remarks – Conversions
You can convert one data structure to another type,
if it is meaningful. Use python built-in functions!
List to tuple and vice-versa
Example (list to tuple):
>>> listX = [-1,20,0, 15,18]
>>> print(listX)
>>> tupleX = tuple(listX) #use the tuple() built-in function
>>> print(tupleX)
Example (tuple to list):
>>> Y= (4,5)
>>> listY = list(Y) #use the list() built-in function
>>> print(listY)
(c) Bharadwaj V Dept of ECE NUS (2023) 19
Final remarks – Conversions
List to arrays and vice-versa
Example (List to array):
>>> from array import array
>>> array1 = array.array('b', [1,2,3,4])
>>> print(‘Original array: ‘, array1)
>>> L = array1.tolist() # alternatively use built-in function
>>> print(L)
Example (Array to list): obvious!
(c) Bharadwaj V Dept of ECE NUS (2023) 20