Module - 2
Data Structure in Python
Syllabus
Lists: Using Lists, List Traversal, List Membership, List
Assignments and Equivalence, List Bounds, Slicing, List
Element Removal, List Methods
Tuples – Creation, Iterating Tuples, Zip and Unzip,
Methods
Dictionaries and Sets – Creation, Iterating values, methods
Python Libraries: NumPy and Pandas
Data Structure
Lists
Lists: A list is an ordered collection of items that can be
changed or modified.
Characterstics: 1. Mutable 2. Ordered 3. Allows Duplicates
Python has a great built-in list type named "list". List
literals are written within square brackets [ ]
Lists in Python of containers of values of different data
types in contiguous blocks of memory. A list can have any
data type, including list, tuples, etc., as its element.
Accessing elements
Elements are accessed using their index, which starts at 0 for the first
element. Negative indexing can also be used, where -1 refers to the last
element.
Slicing: We can access more than one element from a list again using indexing.
These indexes can be positive or negative.
If we want to access all the elements from ‘ith’ index to ‘jth’, jth exclusive,
then we give indexing as ‘i:j’
Reassigning the values: We can change a value, a set of values using the
indexing.
Traversing the List
Iteration is the process of going through each element of
the list. The most common approach is to use the ‘for
loop’. A variable is used as an iterator to go through the
list till it reaches the end/empty value
List Bounds
Lists in Python are ordered collections of items, and each
item in a list has a specific index. The indices start from 0
and go up to length - 1 . Accessing an index outside this
range will result in an IndexError .
Lower Bound is 0 and length of list upper bound len()-1.
Upper Bound: An index of [-1] means "the last element
(length - 1)
List Comprehension
A comprehension is used like an operation on the data set (whether it is a list, dict,
or set) that is generally a few lines of code and shrinks to a single or multiple lines,
thereby increasing the readability and making the code compact.
There is mainly four types of comprehension in python:
List Comprehension
Dictionary Comprehension
Set Comprehension
Generator Comprehension
output_list = [expression for variable in input_list if (condition)]
Main Ways to Remove an Item from a
Python List
remove(): Remove a specific item by its value.
pop(): Remove an item by its index, or the last item.
del : Remove an item by its index or a slice.
clear(): Remove all items from the list.
Methods of List
[Link](elem)
[Link](index, elem)
[Link](elem)
[Link](elem)
[Link]() and sorted(iterable,key,reverse)
[Link]()
[Link](index)
[Link](L)
[Link](i, x)
Tuple
A tuple is similar to a list, but with a key difference: tuples
are immutable. This means that once a tuple is created,
you cannot change its contents (you cannot add, remove,
or modify items).
Creating tuple in Python
To create an empty tuple we just need to assign the square
brackets to the variable as shown below. We can use the type()
function to check the data type.
tup1=()
print("The type of", tup1,"is:", type(tup1))
Creating Python tuple with single element
Creating Python tuple with multiple elements
Accessing elements of tuples in Python
1. To access an element from a list we can write the tuple
name followed by the index in square brackets.
[Link] get the elements from index i to j, excluding the jth,
we give “i:j” indexing.
3. To get all the elements from the index i, we give “i:”
indexing.
4. To get all the elements before index i, excluding the ith,
we give “:i” indexing.
Python Lists vs Tuples
1. The execution time is faster for the tuples because of
their immutability
2. For the same reason, the tuples are memory efficient
compared to the lists
3. Tuples help in the scenarios where we want the data to
not be modified and have read-only property.
4. Tuples can be used as keys for the dictionaries as
dictionary keys are immutable, but this is not possible with
lists
Python Methods
Python Tuple Methods
Because of its immutability, we cannot use some of the
methods like:
1. append() and extend(), insert()because we cannot add
elements to the tuple
2. remove() and pop(), because we cannot delete
elements of a tuple
Methods Allows are
1. Index
Sum
Min
Max
Count
Any
Zip
zip() Return Value
The zip() function returns an iterator of tuples based on the iterable
objects.
If we do not pass any parameter, zip() returns an empty iterator
If a single iterable is passed, zip() returns an iterator of tuples with each
tuple having only one element.
If multiple iterables are passed, zip() returns an iterator of tuples with
each tuple having elements from all the iterables.
The * operator can be used in conjunction with zip() to unzip the list.
Application of Zip
[Link] traversal and soring of the list
2. Processing the corresponding values from multiple
sequences:
Dictionary
In Python, dictionaries are the data types/ data structures that hold key-value
pairs.
Dictionaries are:
Mutable
Ordered in Python version 3.7 and not ordered in the earlier versions
Dynamic – can add and delete values from a dictionary.
Can be nested, a dictionary can have a dictionary as its element. It can
also contain any other data types like lists, tuples, etc.
It does not allow duplicate keys
How to Create Dictionaries in Python?
1. Dictionaries are enclosed by the curly brackets ({}) with
each key-value pair separated by a comma. And the key and
values are related using a colon (:).
2. Using Python dict() function:Another way to create a
dictionary is to use the dict() function,
[Link] duplicate keys in Python: If we try to use the same
key again while creating a dictionary, the new value replaces
the old value corresponding to that key.
4. Creating an empty dictionary in Python and adding
elements:
Accessing the element
1. Using get()
[Link] an element using key in Python
3. Accessing inner elements of container values in Python
Modifying Dictionaries in Python
1. Reassigning a value
2. Adding a new key-value pair in Python
3. Deleting a key-value pair in Python: del [key]
Methods
1. Keys()
[Link]()
[Link]()
[Link](‘key’)
[Link]()
[Link]():They copy() method returns a copy (shallow copy) of the dictionary.
7. pop(key)
[Link]()-Last item
[Link]()-One element is updated to the existing dictionary
Set
A set is an unordered and mutable collection of unique
elements. It works based on another data structure called
a hash table. Because of this, it is advantageous over the
lists while checking for an element in a set.
Sets allows set of string or tuple but not list because it is
not hashable
Create the Set
Using set constructor
s={2,4,’s’}
Methods
update()- used to update the set with union of others and itself
add()- used to add a single item to the set
copy()- used to return a copy of the set
clear()- used to remove all items of the set
discard()- used to remove an item from the set. If the item is not
an element, then nothing is done
union()- used to return a new set as a union of sets
difference()- used to return a new set as the difference of two or more
sets
difference_update()- used to remove intersecting items from this set
intersection()- used to return a new set as intersection of two sets
intersection_update()- used to update a set with the intersection of
another set and itself
pop()- used to return and remove an arbitrary set item, KeyError is
raised if the set is empty
remove()- used to remove an item from the set. KeyError is raised if
an item is not a member of the set
issubset()- if another set is contained in this set, return true
issuperset()- if this set is contained in another set, return true
isdisjoint()- if the intersection of two sets is null, return true
symmetric_difference- used to return a new set as the
symmetric difference of two sets
symmetric_difference_update()- used to update a set with
the symmetric difference of another set and itself
sets support x in set, len(set), and for x in set. Being an
unordered collection, sets do not record element position
or order of insertion.
Frozen Set
The built-in frozenset data type is similar to a set, but
it’s immutable. This means that once a frozenset is
created, its elements can’t be changed, added, or
removed.
Frozensets are useful when you need a set that should
remain constant throughout the program’s execution:
frozenset([iterable])
Return a new set or frozenset object whose elements are
taken from iterable. The elements of a set must
be hashable.
Python Libraries: NumPy
Numpy: NumPy (Numerical Python) is an open source
Python library that’s widely used in science and
engineering.
The NumPy library contains multidimensional array data
structures, such as the homogeneous,
N-dimensional ndarray, and a large library of functions that
operate efficiently on these data structures.
Most NumPy arrays have some restrictions. For instance:
All elements of the array must be of the same type of data.
Once created, the total size of the array can’t change.
The shape must be “rectangular”, not “jagged”; e.g., each row of a
two-dimensional array must have the same number of columns.
It is a library that provides a multidimensional array object, various
derived objects (such as masked arrays and matrices), and an
assortment of routines for fast operations on arrays, including
mathematical, logical, shape manipulation, sorting, selecting, I/O,
discrete Fourier transforms, basic linear algebra, basic statistical
operations, random simulation and much more.
NumPy is a package for scientific
computing.
Multi dimensional array
Methods for processing arrays
Element by element operations
Mathematical operations like logical, Fourier transform,
shape manipulation, linear algebra and random number
generation
How to create a basic array
[Link](),
[Link](),
[Link](),
[Link](),
[Link]()
Many operations can be performed on
NumPy arrays which makes them very
helpful for manipulating data
Selecting array elements
Slicing arrays
Reshaping arrays
Splitting arrays
Combining arrays
Numerical operations (min, max, mean, etc)
Numpy Vectorisation
NumPy vectorization involves performing mathematical
operations on entire arrays, eliminating the need to loop
through individual elements.