2-Data-Structure
2-Data-Structure
Weblink: https://docs.python.org/3.3/tutorial/appetite.html
Sequence (Python) In Python, sequence is the generic term for an ordered set.
There are three basic sequence types: lists, tuples, and range objects.
x not in seq
False, when x is found in the sequence seq, otherwise
True
x+y
Concatenate two sequences x and y
x * n or n * x
Add sequence x with itself n times
seq[i]
ith item of the sequence.
seq[i:j]
Slice sequence from index i to j
seq[i:j:k]
Slice sequence from index i to j with step k
len(seq)
Length or number of elements in the sequence
min(seq)
Minimum element in the sequence
max(seq)
Maximum element in the sequence
seq.count(x)
Count total number of elements in the sequence
seq.append(x)
Add x at the end of the sequence
seq.clear()
Clear the contents of the sequence
seq.insert(i, x)
Insert x at the position i
seq.pop([i])
Return the item at position i, and also remove it from
sequence. Default is last element.
seq.remove(x)
Remove first occurrence of item x
seq.reverse()
Reverse the list
Examples:
if 30 in myList1:
print('30 is present')
output
30 is present
**************************************************
print(max(myList2))
output
96
**************************************************
print(myList2.count(42)) #42 has two times in the list
output
2
**************************************************
print(myList2[2:7])
output
[79, 42, 85, 96, 23]
**************************************************
print(myList2[2:7:2])
output
[79, 85, 23]
**************************************************
myList1.append(60)
print(myList1)
output
[10, 20, 30, 40, 50, 60]
**************************************************
myList2.insert(5, 17)
print(myList2)
output
[56, 42, 79, 42, 85, 17, 96, 23]
**************************************************
myList2.pop(3)
print(myList2)
output
[56, 42, 79, 85, 17, 96, 23]
**************************************************
myList1.reverse()
print(myList1)
output
[60, 50, 40, 30, 20, 10]
**************************************************
myList1.clear()
print(myList1)
output
[]
Weblink: https://docs.python.org/3.3/tutorial/datastructures.html#tuples-and-
sequences
Weblink: https://artofproblemsolving.com/wiki/index.php/Sequence_(Python)
Lists
• It is a sequence in which elements are written as a list of comma separated values
between square brackets.
• The key feature of a list is that it can have elements that belong to different data
types.
The syntax:
List_variable = [ value1, value2]
Example: 1
list_a = [1,2,3,4,5]
print(list_a)
Output: [1, 2, 3, 4, 5]
*******************************************************
Example: 2
list_a = [1,'A',"bcd"]
print(list_a)
Output: [1, 'A', 'bcd']
To access values in lists square brackets are used to slice along with the index or indices
to get value stored at that index.
Syntax:
sequence = list[start:stop:step]
Example: #program to demonstrate the slice operations used to access the elements of
the list.
num_list = [1,2,3,4,5,6,7,8,9,10]
print("num_list is:", num_list)
print("first element in the list is", num_list[0])
print("num_list[2:5]=",num_list[2:5])
print("num_list[::2]=", num_list[::2])
print("num_list[1::3]=", num_list[1::3])
Output:
Example
num_list = [1,2,3,4,5,6,7,8,9,10]
num_list.append(2000)
print("list after appending a value is", num_list)
del num_list[3]
print("list after deleting a value is:",num_list)
Output
Example: #program to illustrate deletion of numbers from a list using del statement
Output
[]
Example: #program to insert a list in another list using the slice operation
Output
Nested Lists
Output
num_list[ 0 ]= 1
num_list[ 1 ]= 2
num_list[ 2 ]= 3
num_list[ 3 ]= 4
num_list[ 4 ]= 5
num_list[ 5 ]= 6
num_list[ 6 ]= 7
num_list[ 7 ]= 8
num_list[ 8 ]= 9
num_list[ 9 ]= 10
num_list[ 10 ]= PYTHON WITH JULIA CALLED 1.2 RELEASED
num_list[ 11 ]= [1000, 2000, 300]
num_list[ 12 ]= 3.142
num_list[ 13 ]= 4.142
num_list[ 14 ]= 5.142
Cloning Lists
If you want to modify a list and also keep a copy of the original list, then you should
create a separate copy of the list. This process is called cloning.
Example: #Program to create a copy as well as the clone of the original list
list1 = [1,2,3,4,5,6,7,8,9,10]
list2 = list1 #copy is a list using reference
print("list1 =", list1)
print("list2 =", list2) #both lists point to the same list
list3 = list1[2:6]
print("list3=",list3) #list is a clone of list1
Output
List Methods:
Note: insert (), remove (), sort () methods only modify the list and do not return any
value.
If you print the return values of these methods, you will get none, because a design
principle that is applicable to all mutable data structures in python.
list1 = ['1','a',"abc",'2','B',"Def"]
list1.sort()
print(list1)
Output
['1', '2', 'B', 'Def', 'a', 'abc']
Note: sort method uses ASCII values to sort the values in the list.
That is upper case letters comes before lowercase and numbers comes even before the
upper case letters.
Using Lists as Stack:
What is Stack?
Stack is a linear data structure which uses the LIFO format (Last in First Out) data
structure, as the element that was inserted last is the first one to be taken out.
Stack supports three basic operations: push, pop and peep (peek)
stack = [1,2,3,4,5,6]
print("Original Stack is:", stack)
stack.append(7)
print("Stack after the push opertion is:", stack)
stack.pop()
print("Stack after the pop operation is:", stack)
last_element_index = len(stack)-1
Output:
Queue is an important data structure which stores its elements in an ordered manner.
A queue is a FIFO (First in First Out) data structure in which the element that is inserted
in the first is to be taken out.
The elements in a queue are added at one end and removed from the other end.
Queue supports three basic operations: insert, delete, and peep (peek)
• Insert ()-in queue the append () method is used to insert the element at the end of
the queue.
• Delete () - in queue the pop () method used with the index 0 (zero) to delete the
first element from the queue.
• Peep () - the slice operation to print the value of the last element in the queue.
queue = [1,2,3,4,5,6]
print("Original Stack is:", queue)
queue.append(7)
print("Stack after the push opertion is:", queue)
queue.pop(0)
print("Stack after the pop operation is:", queue)
last_element_index = len(queue)-1
Output
Output
Cubes of numbers form 1-10: [0, 1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
• In list comprehension, the expression is evaluated once for every item in the
sequence.
• List comprehension is also used to create a subsequence of those elements that
satisfy a certain condition.
Example 2
Output
Example 3: # Program to combine and print elements of list using list comprehension
Output
[(10, 30), (10, 40), (10, 50), (20, 30), (20, 40), (20, 50), (30, 40), (30, 50)]
Looping in Lists:
Python’s for and in constructs is extremely useful especially when working with lists.
The for var in list statement is an easy way to access each element in a list.
• This function is used to when you want print both index as well as an item in the
list.
• The enumerate function object which contains the object and value of all the
items of the list as a tuple.
# Program to illustrate the use of enumerate () to print an individual item and its index
in the list
num_list = [1,2,3,4,5,6,7,8,9,10]
Output
1 is at index: 0
2 is at index: 1
3 is at index: 2
4 is at index: 3
5 is at index: 4
6 is at index: 5
7 is at index: 6
8 is at index: 7
9 is at index: 8
10 is at index: 9
Tuple:
Creating a Tuple is very simple and can be created using the comma-separated values
within parentheses.
Examples:
Output:
()
5
(1, 2, 3, 4, 5)
('A', 'B', 'C', 'D')
('SHIV', 'SHRU', 'RAJ')
(3.142, 15.84, 22, 78)
(1, 'SHIV', 3.142, 'F')
If you want create a tuple with a single element, and then you must add a comma after
the element. In the absence of a comma, python treats the element as an ordinary data
type.
Example:
Output:
<class 'int'>
<class 'tuple'>
To access values in tuple slice operation used along with the index.
tuple = (10,20,40,30,60,50,70,90,80,100)
print("tuple[:]=",tuple[:])
print("tuple[:5]=",tuple[:5])
Output:
tuple[:]= (10, 20, 40, 30, 60, 50, 70, 90, 80, 100)
tuple[:5]= (10, 20, 40, 30, 60)
Updating Tuple:
Tuple is immutable and so the values(s) in the tuple cannot be changed, you can only
extract values from a tuple to form another tuple.
Since tuple is an immutable data structure you cannot delete value(s) from it.
tuple1 = (10,20,40,30)
del tuple1[3]
print(tuple1)
Output
However, you can always delete the entire tuple by using the Del statement.
tuple1 = (10,20,40,30)
del tuple1
print(tuple1)
Output
Note: the name error occurs because; you are now trying to print a tuple that has
already been deleted.
Operation Expression
Length Len((1,2,3,4,5))
Concatenation (1,2,3)+(4,5,6)
Repetition (“GOOGLE”)*3
Membership 5 in (1,2,3,4,5,6,4,7,8,9)
Iteration For i in (1,2,3,4,5,6,4,7,8,9):
Comparison (use >,<, ==) Tup1 = (1,2,3,4,5)
Tup2 = (1,2,3,4,5)
Print(Tup1 > Tup2)
Maximum Max(1,0,3,8,2,9)
Minimum Min(1,0,3,8,2,9)
Tuple Assignment:
Output
123
Example
Output
When we need to return more than one value from a function, in such situation it is
preferable to group together multiple values and return them together.
Example: Program to return the Highest and Lowest values in the list
def max_min(values):
x = max(values)
y = min(values)
return (x,y)
values = (100,45,80,90,15)
(max_marks, min_marks) = max_min(values)
Lowest marks: = 15
Nested Tuples:
Python allows defining a tuple inside another tuple and this is called nested tuple.
For example, we have a list of players who have topped in their respective sports. We
store the Name, Sport, and Average runs of three players as Tuples inside the tuple
toppers.
topper = (("Yuvraj","Cricket",100),
("Bolt","Running",100),("Dhoni","Cricket",100))
for i in topper:
print(i)
Output
The index of an element in the tuple can be obtained by using the index ( ) method.
Source Code
stu = ("A","B","C","D")
index = stu.index("D")
print("D is present at index:", index)
Output
D is present at index: 3
Counting the Element: Count () Method
The count () method is used return the number of elements with a specific value in a
tuple.
Example: program to count the number of times letter ‘X’ appears in the specified
string.
Source Code
tuple = "abcdxxxxefghxxxxijklxxxxmnopxxxxqrstxxxxuvwxxxxxyz"
print("x appears",tuple.count('x'),"times in",tuple)
Output
x appears 25 times in
abcdxxxxefghxxxxijklxxxxmnopxxxxqrstxxxxuvwxxxxxyz
• The zip () is a built-in function that takes two or more sequences and zips them
into a list of tuples.
• The zip () function is a list of tuples where each tuple contains a character from
the list and an integer from the tuple.
• To perform zip () we should have equal number of values in the list and tuple.
Source Code
value11 = (1,2,3)
value22 = ['A','B','C']
print(list(zip(value11,value22)))
Output
Tuple List
Tuples are used to store values of different Lists are used to store values of same/
data types similar data types
Tuples are immutable Lists are mutable
Tuples can be used as key for a dictionary Lists cannot be used as keys
Tuples are best used for storing data Lists are also used for storing data but in
which is write protected that is data once lists we can change / alter the list.
stored cannot be changed
SETS:
A set () data structure supported by python and it is created using / by placing all the
elements inside the curly brackets { }.
Source Code
value11 = [1,2,3]
print(set(value11))
Output
{1, 2, 3}
Source Code
Output
• Union: Union of two sets includes all elements from both the sets
• Intersection: Intersection of two sets includes elements that are common to both
the sets
• Difference: Difference of set 1 and set 2 includes all elements are in set 1 but not
in set 2.
• Symmetric difference: Symmetric difference of set1 and set2 includes all
elements that are in set1 and set2 but not the one that are common to set1 and
set2.
Source Code
cricket = set(["Dhoni","Yuvraj","Bolt","Sachint","Sganguly"])
analyst= set(["Ravis","Sganguly","Sachint"])
print("=================================================
======================================")
print("cricket:",cricket)
print("---------------------------------------------------------------------------------------")
print("analyst:",analyst)
print("---------------------------------------------------------------------------------------")
print("People playing as cricket's as well as analyst:",
cricket.intersection(analyst))
print("---------------------------------------------------------------------------------------")
print("People playing as cricket's as well as analyst:",
cricket.union(analyst))
print("---------------------------------------------------------------------------------------")
print("People playing as cricket's as well as analyst:",
cricket.difference(analyst))
print("---------------------------------------------------------------------------------------")
print("People playing as cricket's as well as analyst:",
cricket.symmetric_difference(analyst))
print("=================================================
======================================")
Output
======================================================
=================================
cricket: {'Bolt', 'Sachint', 'Dhoni', 'Sganguly', 'Yuvraj'}
---------------------------------------------------------------------------------------
analyst: {'Sganguly', 'Sachint', 'Ravis'}
---------------------------------------------------------------------------------------
People playing as cricket's as well as analyst: {'Sganguly', 'Sachint'}
---------------------------------------------------------------------------------------
People playing as cricket's as well as analyst: {'Dhoni', 'Sganguly', 'Ravis',
'Bolt', 'Sachint', 'Yuvraj'}
---------------------------------------------------------------------------------------
People playing as cricket's as well as analyst: {'Dhoni', 'Bolt', 'Yuvraj'}
---------------------------------------------------------------------------------------
People playing as cricket's as well as analyst: {'Bolt', 'Dhoni', 'Ravis',
'Yuvraj'}
======================================================
=================================
Set Operations:
• Dictionary is a data structure in which we store values as a pair of key and value.
• Each key is separated from its value by a colon (:) and consecutive items are
separated by commas.
• The entire items in a dictionary are enclosed in curly brackets { }.
Syntax:
Creating a Dictionary:
Output: { }
• To create a dictionary with one or more key-value pairs you can also use the dict
() function.
• The dict () creates a dictionary directly from a sequence of key value pairs.
print(dict((('jersey','7'),('Name','Dhoni'),('Sport','Cricket'))))
Output
Accessing Values:
• To access values from a dictionary square brackets are used along with the key to
obtain its value.
Source code
print("jersey:", dictionary["jersey"])
print("Name:", dictionary["Name"])
print("Sport:", dictionary["Sport"])
Output
jersey: 7
Name: Dhoni
Sport: Cricket
Source code
#if you try to access an item with a key which is not specified in the dictionary, a key
Error is generated
print("marks:=", dictionary["marks"])
Output
• To add a new entry or a key value pair in a dictionary you must specify the key-
value pair.
Source Code
dictionary = (dict((('jersey','7'),('Name','Dhoni'),('Sport','Cricket'))))
print("jersey:", dictionary["jersey"])
print("Name:", dictionary["Name"])
print("Sport:", dictionary["Sport"])
Output
jersey: 7
Name: Dhoni
Sport: Cricket
Marks is the new item added to a dictionary
Marks: 95
Deleting Items:
• The keys() method of dictionary returns a list of all the keys used in the
dictionary in arbitrary order.
• The sorted () function is used to sort the keys.
Source Code
dictionary = (dict((('jersey','7'),('Name','Dhoni'),('Sport','Cricket'))))
print(sorted(dictionary.keys()))
Output
Source Code
Output
Operation Description
len(dict) Returns the length of dictionary. That is number of items(key-
value pairs)
str(dict) Returns a string representation of the dictionary
dict.clear() Deletes all entries in the dictionary
dict.copy() Returns a shallow copy of the dictionary, i.e. the dictionary
returned will not have a duplicate copy of dict but will have the
same reference
dict.get(key) Returns the value for the key passed as argument.
dict.has_key() Returns True if the key is present in the dictionary and False
otherwise
dict.items() Returns a list of tuples
dict.keys() Returns a list of keys in the dictionary
dict1.update(dict2) Adds the key-value pairs of dict1 to the key-value of dict2
dict.values() Returns a list of values in dictionary
dict.iteritems() Used to iterate through items in the dictionary
In and not in Checks whether a given key is present in dictionary or not
Python allows string formatting with dictionaries with the help of %S, %D, %F to
represent sting, integer and float values.
Source Code
#Program that uses string formating feature to print the key-value pairs stored in the
dictionary
Output
Programs:
Program 1
Write a program that has dictionary of names of students and a list of their marks in
four subjects. Create another dictionary from this dictionary that has name of the
student and their total marks. Find out topper and his/her score.
Source Code
Marks=
{"Shivaraj":[45,78,75,65],"Shruthi":[65,70,70,70],"Kirthi":[80,50,45,60],"Shwetha":[45
,55,60,70]}
total = 0
total_marks = Marks.copy()
for key,val in Marks.items():
total = sum(val)
total_marks[key] = total
print(total_marks)
max = 0
topper = ''
for key, val in total_marks.items():
if val>max:
max = val
topper = key
print("Topper is : ", topper, "with marks=",max)
Output
Program 2
Write a program that generates a set of prime numbers and another set of odd numbers.
Demonstrate the result of union, intersection, difference and symmetric difference
operations on these sets.
Source Code
print(odds)
prime = set()
for i in range(2,20):
j=2
flag = 0
while j<i/2:
if i%j == 0:
flag = 1
j+=1
if flag == 0:
prime.add(i)
print(prime)
print("union:", odds.union(prime))
print("intersection:", odds.intersection(prime))
print("difference:", odds.difference(prime))
print("symmetric_difference:", odds.symmetric_difference(prime))
output
Program 3
Write a program that creates a list of 10 random integers. Then create ODD list and
EVEN list that has all odd and even values in the list respectively?
Source Code
list1 = [11, 22, 33, 44, 55, 50, 19, 75, 60, 80]
# check and append odd numbers in listOdd and even numbers in listEven
# print lists
print ("list1: ", list1)
print ("listEven: ", listEven)
print ("listOdd: ", listOdd)
Output
list1: [11, 22, 33, 44, 55, 50, 19, 75, 60, 80]
listEven: [22, 44, 50, 60, 80]
listOdd: [11, 33, 55, 19, 75]
Program 4
Write a program to print index at which a particular value exists. If the value exits at
multiple locations in the list, then print all the indices. Also, count the number of times
that value is repeated in the list.
Source Code
num_list = [1,2,3,4,5,6,5,4,3,2,1]
num = int(input("Enter the values to be searched:"))
i=0
count = 0
while i<len(num_list):
if num == num_list[i]:
print(num,"found at location", i)
count+=1
i+=1
print(num,"appears", count, "times in the list")
Output
***************************************************************************************
Good Luck