3.1_3.2_3.3_3.4 Data Structures in Python
3.1_3.2_3.3_3.4 Data Structures in Python
Ms. G. D. Patne
Lecturer in Computer Engg.
Government Polytechnic Ratnagiri
Content
Introduction
Lists
Tuples
Sets
Dictionaries
Introduction
A data structure is specialized format for organizing and storing data,
so that various operations can be performed on it efficiently and
easily.
Any data structure is designed to organize data to suit a specific
purpose so that it can be accessed and worked with in appropriate
and systematic manner.
There are four data structures in Python, List, Tuples, Sets and
Dictionaries.
A data structure that stored an ordered collection of items in Python is
called a list.
In other words it holds a sequence of items or elements.
Similar to a list, the tuple is an ordered sequence of items.
A set is an unordered collection of unique items in Python.
A dictionary in Python is an unordered collection of key value pairs.
The data types that are most used in Python are string, tuples, list and
dictionaries.
Lists
A list in Python is a linear data structure.
The elements in the list are stored in a linear order one after
another.
A list is a collection of elements.
The element in a list can be accesses by their positions i.e.
indices.
The index in lists always starts with 0 and ends with n-1, if the list
contains n elements.
In Python lists are written with square brackets [].
A list is created by placing all the elements inside a square
brackets, separated by commas.
Syntax:
<list name>=[value1, value2,….value n]
Example:
Emp=[20,’amar’, ‘M’, 30]
List are mutable or changeable.
The value of any element inside list can be changed at any point of time.
A list data type is flexible data type that can be modified according to the
requirement.
Creating a List
Accessing value in List
Accessing elements from a
list in Python programming is
a method to get values that
are stored in the list at a
particular location or index.
To access values in lists, use
the square brackets for
slicing along with the index
obtained value available at
that index.
Accessing elements from a
particular list in Python at
once allows the user to
access all the values from
the lists.
This is possible by writing
the list name in the print()
statement.
E.g. print(L)
Deleting Values in List
Python provides many ways in which the elements
in a list can be deleted.
1. pop() method in python is used to remove a
particular element from the given index in the list.
By default it removes and returns the last element
if index is not provided.
2. We can delete one or more elements from
a list using the keyword ‘del’. It can even
delete the list entirely.
But it does not store the value for further
use.
3. The remove() method in Python is used
to remove a particular element from the list.
We use the remove() method if we know the
element that we want to remove or delete
from the list (not index).
Updating Lists
List are mutable, meaning their element can be changed or updated.
Mutability is the ability for certain types of data to be changed without entirely
recreating it.
Using mutable data type can allow programs to operate quickly and efficiently.
Multiple values can be added into list.
We can use assignment operator (=) to change an item or a range of items.
We can update items of the list by simply assigning the value at the particular
index position.
We can also remove the items from the list using remove() or pop() or del
statement
List methods used for updating list:
Sr. Method Syntax Argument Return Type
No Description
.
1 append() List.append(item) The item can be Only modifies
numbers, strings, the original
another list, list. It does
dictionary, etc not return any
value
2 extend() List1.extend(list2) Takes a list and Only modifies
adds it to the the original
end list. It doesn’t
return any
value
3 Insert() List.insert(index,eleme This index is It does not
nt) position where return
an element anything:
needs to be returns none
inserted element-
The element to
be inserted in the
list
+ operator
and *
Operator
Sort() method
Basic List Operations
1. Indexing:
An individual item in the list can be referenced by using an index,
which is an integer number that indicates the relative position of the
item in the list.
We can use the index operator [] to access an item in a list. Index
start from 0. so a list having 5 elements will have index from 0 to 4.
Python allows negative indexing for its sequences.
The index of -1 refers to the last item , -2 to the second last item and
so on.
List Slicing
Slicing is an operation that allows us to extract elements
from units.
The slicing feature used by python to obtain a specific subset
or element of the data structure using colon (:) operator.
Syntax:
› List_var[start_index:end_index]
Will return the subset of the list starting from start_index to on index
less than that of the end index.
List Slicing with step
size:
Traversing a List:
Traversing a list means accessing all the elements of
the list.
Traversing can be done by using any conditional
statement of Python, but it is preferable to use for loop.
Built-in Functions and Methods for List:
Sr.No Function with Description
1 cmp(list1, list2)
Compares elements of both lists.
2 len(list)
Gives the total length of the list.p>
3 max(list)
Returns item from the list with max value.
4 min(list)
Returns item from the list with min value.
5 list(seq)
Converts a tuple into list.
6. sum(list)
Calculate sum of all the elements of list.
Methods of List Class:
Sr.No Methods with Description
1 list.append(obj)
Appends object obj to list
2 list.count(obj)
Returns count of how many times obj occurs in list
3 list.extend(seq)
Appends the contents of seq to list
4 list.index(obj)
Returns the lowest index in list that obj appears
5 list.insert(index, obj)
Inserts object obj into list at offset index
6 list.pop(obj=list[-1])
Removes and returns last object or obj from list
7 list.remove(obj)
Removes object obj from list
8 list.reverse()
Reverses objects of list in place
9 list.sort([func])
Sorts objects of list, use compare func if given
Tuples
A tuple is also a linear data structure.
A python tuple is a sequence of data values called as
items or elements.
Each element or value that is inside of tuple is called an
item.
A tuple is a collection of items which is ordered and
unchangeable.
A tuple data structure that is immutable means you can
not add and remove items from the tuple..
Their values cannot be modified.
A tuple is a heterogeneous data structure and used for
grouping data.
In python tuples are written with round bracket () and
values in tuples can be accessed by their index values,
which are integer starting from 0.
Values are separated by comma (,).
Creating Tuple
To create tuple, all the elements are placed inside parenthesis()
separated by commas and assigne to a variable.
Syntax:
› <tuple_Name>= (value1, value2,….valuen)
Example: emp=(20,”ABC”,’M’, 30)
A tuple in Python is immutable data type which means a tuple
once created cannot be modified.
Tuples can have any number of different data items.
Accessing value in Tuple
Accessing elements from the tuple is a method to get
values stored in the tuple from a particular location or
index.
Deleting Tuples
Tuples are unchangeable, so we cannot remove
elements from it., but we can delete the tuple
completely.
To explicitly remove an entire tuple, just use the
del statement.
Updating Tuple
Tuple are immutable which means we cannot update or
change the values of tuple element.
We are also able to take portions of existing tuples to create
new tuples.
Tuple Operations
Built in Functions of Tuple
Sets
The set data structure in Python programming is implemented
to support mathematical set operations.
Set is an unordered collection of unique elements.
Elements stored in a set are not kept in any particular order.
Sets are unindexed that means we cannot access set elements
by referring to an index.
Sets are changeable(mutable), i.e we can change a set as and
when required.
Type of elements in a set need not to be same, various mixed
data type values can also be passed to the set.
Set operations: Union, Intersection, difference, complement
etc.
Set is defined by values separated by comma inside curly
brackets { }.
Syntax:
Remove
Pop:
Clear:
Updating Set
intersection_update() Updates the set with the intersection of itself and another
>>>square={1:1,2:4,3:9,4:16}
print(1 in square)
2. Traversing Dictionary:
Using for loop we can iterate through each key in dictionary.
Example:
>>>square={1:1,2:4,3:9,4:16}
>>> for I in square:
print(i,square[i])
Built in Methods for dictionary
Method Description
clear() Removes all items from the dictionary.
copy() Returns a shallow copy of the dictionary.
>>>”Hello”+”Python”
HelloPython
* Operator:
The multiplication operator is used to
concatenate the same string multiple times.
It is called repetition operator.
Example:
>>> s1=“Hello”
>>>s2=3*s1
‘Hello Hello Hello’
String Traversal:
Traversal is a process in which we
access all the elements of the string
one by one using for and while loop.
Example:
>>> s=“Welcome”
>>>for c in s:
print(c,end=“”)
Immutable Strings:
› Strings are immutable means we can not
change any element of a string.
› If we want to change an element of a string,
we have to create a new string.
› Example:
>>> str=“Python”
>>>str[0]=“H”
Error
Use
>>>str1=‘H’+str[1:]
>>>str1
String Indices and Accessing string
Elements:
‘in’ and ‘not in’ operator in Strings:
› The ‘in’ operator is used to check whether
a character or a substring is present in a
string or not.
› The expression returns a Boolean value.
› Example:
>>> s=“Hello”
>>> ‘He’ in s
True
String Slicing:
› A piece of string is known as slice.
› To cut a substring from string is called string
slicing.
› Slice operator is applied to a string with the
use of square bracket[].
› Ending limit exclude the last index (n-1).
› A slice 3:7 means 3rd, 4th, 5th and 6th position
character.
› Syntax:
Stringname[start_index:end_index]
Stringname[start_index:end_index: step_size]
› Example:
>>>s=“Hello”
>>>s[0:2]
he
Special Charctaer in String
String Formatting Operators
Sr.No Format Symbol & Conversion
1 %c character
2 %s string conversion via str() prior to formatting
6 %o octal integer