0% found this document useful (0 votes)
4 views

Python Chapter-2 (1)

This document provides an overview of Python data structures, including strings, lists, tuples, dictionaries, sets, and hash tables. It explains their characteristics, methods, and operations, along with searching and sorting algorithms. Key concepts such as mutability, indexing, and data organization are highlighted throughout the text.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Python Chapter-2 (1)

This document provides an overview of Python data structures, including strings, lists, tuples, dictionaries, sets, and hash tables. It explains their characteristics, methods, and operations, along with searching and sorting algorithms. Key concepts such as mutability, indexing, and data organization are highlighted throughout the text.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 38

Python Programming

PIET
CSE Dept.
CHAPTER-2
Python Data Structure
What is Data Structure?
➢ Data structure identifies how data or values are stored in memory

Figure 3.1 Python Data Structure


String
➢ Sequence of characters
➢ Keyword for string datatype : str
➢ Uses single or double quotes : 'Hello' or
"Hello"
➢ When a string contains numbers, it is
still a string : ‘123’
➢ Convert numbers in a string into a
number using int()
➢ immutable : Value of sting can not be
changed
input() reads string only
More on String
➢ Get length of string
▪ len()
➢ String slicing using colon operator
▪ st[start : end]
➢ Count the occurrence of character
▪ st.count(‘character)
➢ String uses index
▪ String = ‘World’ is indexed as
follows

W o r l d
0 1 2 3 4
String Library
➢ List of common function provided by string library
➢ Explore more using : dir(string_object)
• capitalize • join
• center • ljust
• count • Lower
• endswith • Lstrip
• find • replace
• Index • rjust
• Isalnum • rsplit
• Isalpha • Rstrip
• Isdigit • Startswith
• Islower • Swapcase
• isupper • upper
List

➢ Collection of many values in a single variable


➢ Mutable : value of list variable can be changed
➢ Uses square brackets : []
➢ Example:

list_of_number = [ 1, 2.3, 3, 4, 0]

Friend_list = [‘kanu’, ‘manu’, ‘tanu’]

City_list = [‘Baroda’, ‘Anand’, 123]

Image source : Google


Exploring List
➢ List is an ordered collection
➢ Access any element using index
➢ Get number of elements : len()
➢ List concatenation : ‘+’
➢ List slicing using colon

nita 12 pavan 13 14
0 1 2 3 4
List Methods
Methods Description

append Add element in the list as it is

count Count the occurrence of an element in list

extend Add values of object as elements of the list

index Get the index of an element

sort Sort the elements of list

insert Add element at specified index

pop Retrieve the last element of list

remove Remove the given element from list

reverse Reverse the sequence of elements in list

clear Empty the list by removing all elements


Playing with List
Playing with List
List Comprehension
➢ Use logical statement to create list
Tuple
➢ Same as list
➢ Immutable : values can not be changed
➢ Use round brackets
Exploring Tuple

➢ Tuple has two method ➢ Tuple as assignment


➢ Count
➢ Index
Dictionary
➢ Unordered collection of data in key : value form
➢ Indexed by unique key Bag of items
➢ Uses curly braces : { }

Image source : Google


Creating Dictionary

OR
Keys as Index

12 75 3
money tissues candy
Dictionary Methods

➢ get()
• give the value at given key if
key is there, otherwise create
given and assign default value

➢ keys() : list of keys


➢ values() : list of values
➢ Items() : list of (key, value)
Counting Pattern
Set
➢ Unordered collection of unique and
immutable objects
➢ set itself is mutable
➢ Uses curly braces : {}

Image source : Google


Exploring Set

➢ add() : add any single element in set

➢ update() : add multiple elements


passed in the form of tuples, list, string
or other set in set

➢ discard()/ remove() : remove element


from set
Frozenset
➢ Frozensets are like sets except that they cannot
be changed
➢ They are immutable

Image source : Google


Set Operation

union (|) intersection (&)

difference (-) symmetric_difference (^) Image source : Google


Set Operation
Stack and Queue

Stack: Stores items in last in first out(LIFO) manner.

The operations of adding and removing the elements is known


as PUSH and POP.
PUSH into a Stack: to add element on top of the stack append() will be
used.
POP from a Stack: to remove element on top of the stack pop() will be
used.
Stack and Queue

Example:
Output:
Stack and Queue

Queue: Stores items on first in first out (FIFO) manner.


Example:
Output:
Hash Tables

Hash tables are a type of data structure in which the address or the
index value of the data element is generated from a hash function.

Hash table stores key-value pairs but the key is generated through a
hashing function.

So the search and insertion function of a data element becomes much


faster as the key values themselves become the index of the array
which stores the data.
Hash Tables

In Python, the Dictionary data types represent the implementation of


hash tables. The Keys in the dictionary satisfy the following
requirements:

• The keys of the dictionary are hashable i.e. the are generated by
hashing function which generates unique result for each unique value
supplied to the hash function.
• The order of data elements in a dictionary is not fixed.

Example : dict= {‘name’:’shree’, ‘age’=25}


print(dict[‘name’])
Output: shree
Searching Algorithms

Searching is the process of looking for a particular value in a collection.


Built-in Python methods:

If we want to know the position of x in a list, the index method can be used.
>>> nums=[3,1,4,2,5]
>>>nums.index(4)
>>>2
Searching Algorithms

Linear Search:

search through the list of items one by one until the target value is found.

index operations implement linear searching algorithms


Searching Algorithms
Binary Search:

If the data is sorted, there is an even better searching strategy – one you
probably already know!
Binary means two, and at each step we are diving the remaining group of
numbers into two parts.
The heart of the algorithm is a loop that looks at the middle element of the
range, comparing it to the value x.

If x is smaller than the middle item, high is moved so that the search is
confined to the lower half.

If x is larger than the middle item, low is moved to narrow the search to the
upper half.
Searching Algorithms
Sorting in Python

Bubble Sort
It is a comparison-based algorithm in which each pair of adjacent elements is
compared and the elements are swapped if they are not in order.
Sorting in Python

Insertion Sort
Insertion sort involves finding the right place for a given element in a sorted list.
So in beginning we compare the first two elements and sort them by comparing
them.
Then we pick the third element and find its proper position among the previous
two sorted elements.
This way we gradually go on adding more elements to the already sorted list
by putting them in their proper position.
Sorting in Python
www.paruluniversity.ac.in

You might also like