Pythonunit 6

Download as pdf or txt
Download as pdf or txt
You are on page 1of 26

Unit VI

Tuples
A tuple is a sequence of values, which can be of any type and they are indexed by integer.
Tuples are just like list, but we can’t change values of tuples in place. Thus tuples are
immutable.
The index value of tuple starts from 0.
A tuple consists of a number of values separated by commas. For example:
>>> T=10, 20, 30, 40
>>> print (T)
(10, 20, 30, 40)
CREATING TUPLE: All the objects-also known as "elements"-must be separated by a
comma, enclosed in parenthesis (). Although parentheses are not required, they are
recommended.
Any number of items, including those with various data types (dictionary, string, float, list,
etc.), can be contained in a tuple.

Features of Python Tuple

 Tuples are an immutable data type, meaning their elements cannot be changed after they
are generated.
 Each element in a tuple has a specific order that will never change because tuples are
ordered sequences.

Code:

# Python program to show how to create a tuple


# Creating an empty tuple
empty_tuple = ()
print("Empty tuple: ", empty_tuple)

# Creating tuple having integers


int_tuple = (4, 6, 8, 10, 12, 14)
print("Tuple with integers: ", int_tuple)

# Creating a tuple having objects of different data types


mixed_tuple = (4, "Python", 9.3)
print("Tuple with different data types: ", mixed_tuple)
# Creating a nested tuple
nested_tuple = ("Python", {4: 5, 6: 2, 8:2}, (5, 3, 5, 6))
print("A nested tuple: ", nested_tuple)
Output:
Empty tuple: ()
Tuple with integers: (4, 6, 8, 10, 12, 14)
Tuple with different data types: (4, 'Python', 9.3)
A nested tuple: ('Python', {4: 5, 6: 2, 8: 2}, (5, 3, 5, 6))

Accessing Elements in a Tuple in Python and Indexing


Accessing elements in a tuple is no different then accessing elements in a list. As python
follows 0 based indexing hence a tuple with n elements will have indices from 0 through
n-1. An index in a tuple is accessed with the index operator [ ]. For example:
Code:
tempTuple = ('hello', 1, 2, 3)
print(tempTuple[0]) # prints first element of the tuple
print(tempTuple[3]) # prints last element of the tuple
print(tempTuple[4]) # error
Output:
Hello
3
Traceback (most recent call last):
File "D:/list.py", line 4, in <module>
print(tempTuple[4]) # error
IndexError: tuple index out of range
Slicing in Tuples
Slicing in tuples works the same as it works for a String slicing or any other sequence of
elements. Slice is an operator that allows you to fetch a sub collection (in this case a sub
tuple) from a collection by slicing it from a start index and a stop index.
syntax:
tuple[start : stop : step]
start: is the starting index of the string, on which slicing operation has to be performed. It
determines from where slicing of the string will ‘begin’.
stop: is the stopping index of the slicing, ‘until’ which slicing operation has to be performed
i.e stop index is excluded while generating the sub-tuple.
step: It is an optional argument that defines the steps when iterating the list i.e. it allows us
to skip over elements.
Code:
temptuple = ("Welcome", "to", "world", "of", "Programming", "a", "great", "day")

tuple1 = temptuple[::] # fetching complete tuple

print("tuple1:", tuple1)

tuple2 = temptuple[0 : 6] # fetching tuple from 0th index to 6th index

print("tuple2:", tuple2)

tuple3 = temptuple[:: 3] # jumping every third element from start to end

print("tuple3:", tuple3)

tuple4 = temptuple[1:5:2] # jumping to every 2nd element starting from 1st index until
5th index

print("tuple4:", tuple4)

tuple5 = temptuple[-8:-5] # 8th index from end to 5th index from end

print("tuple5:", tuple5)

tuple6 = temptuple[::-3] # jumping every 3rd element in reverse

print("tuple6:", tuple6)

tuple7 = temptuple[-7:-3:2] # alternate implementation of tuple4

print("tuple7:", tuple7)

Output:
tuple1: ('Welcome', 'to', 'world', 'of', 'Programming', 'a', 'great', 'day')
tuple2: ('Welcome', 'to', 'world', 'of', 'Programming', 'a')
tuple3: ('Welcome', 'of', 'great')
tuple4: ('to', 'of')
tuple5: ('Welcome', 'to', 'world')
tuple6: ('day', 'Programming', 'to')
tuple7: ('to', 'of')
In-built Functions for Tuple:

Set
In mathematics, a set is a collection of distinct objects forming a group. The objects can be
of any type like numbers, names of movies, company names, etc. There can be any number
of objects in a set and the objects can be of different data types. Set is a concept of Set
Theory which is a popular and useful topic of mathematics. There are several operations
that can be performed on a set, these operations include union, intersection, difference.
Sets in python are also similar but with a few conditions.
1. First, that a set cannot contain duplicate elements.
2. Second, the elements of a set are immutable(once entered cannot be changed) but
the set as a whole is mutable.
In python, operations like union, intersection can be performed on a set, but it is also used
for other purposes which we will discuss in this article.
The formal definition of a set in Python will be: Set is an unordered collection of items,
where every element is unique and immutable. However, the set itself is mutable.
Creating Sets : Just like most other things, creating a set in Python is really simple. There
are two ways of creating a set
1. Putting all the elements inside curly braces “{“ and “}”
2. Using set() method.
1.Using Curly Brace
Code Output
evenNumber = {2, 4, 6} {2 , 4 , 6}
print(evenNumber) {2, 3, 'one'}
stringAndNum = {"one", 2, 3}
print(stringAndNum)
2.Using set() method.
Code Output
setWithMethod = set([1, 2, 'three']) {1, 2, 'three'}
print(setWithMethod)
Adding Items in a Python Set
Adding elements in a set is not the same as adding elements in lists. Set do not use
indexing. There are two methods to add elements in a set
1. add() allows adding single element
2. update() allows to add multiple elements
Let's take a look at the code -
Code Output
initialSet = {1, 2} {1, 2, 3}
initialSet.add(3) {1, 2, 3, 4, 5}
print(initialSet)
toAdd = [4, 5]
initialSet.update(toAdd)
print(initialSet)
Removing Items from a Set in Python
For removing elements we have these methods:
remove(element) - This method removes the element from the set. If the element is not
present then it will throw an error.
discard(element) - This method removes the element from the set. If the element is not
present then the set will remain unchanged.
Clear() - This method is used to delete all the set elements.
Code Output
mySet = {1, 2, 3, 5} Before: {1, 2, 3, 5}
print("Before: ", mySet) After: {1, 2, 5}
mySet.remove(3) Using: {1, 2, 5}
print("After: ", mySet) set()
mySet.discard(4)
print("Using discard: ", mySet)
mySet.clear()
print(mySet)

Set Operations in Python

Most operations on set can be performed in two ways.


1. Using operator
2. Using methods
Union: Union operation combines all the elements from both sets. “|” (pipe) symbol is used
to carry out this operation. We can also use the union() method in Python.
Code Output
S1 = {14, 13, 22} {1, 2, 22, 13, 14}
S2 = {1, 2, 13} {1, 2, 22, 13, 14}
print(S1| S2) #Union by operator
print(S1.union(S2)) #union by method
union()
Intersection: Intersection operation picks the elements that are common in both
sets. “&” operator or intersection() method is used to perform this operation.
Code Output
S1 = {14, 13, 22,12} {12, 13}
S2 = {1, 2, 13,12} {12, 13}
print(S1&S2) #intersection by
operator
print(S1.intersection (S2)) #intersection by
method union()
Difference: The difference in sets is similar to subtraction. When set B is subtracted from
set A i.e, Set A - Set B then we say that in the resulting set all the elements of Set B will be
removed from Set A. “-” (subtraction sign) or difference() method is used to perform this
operation.
Code Output
S1 = {'Python', 'JavaScript', 'C++'} {'JavaScript' , 'Python'}
S2= {'Assembly', 'C++'} {'JavaScript' , 'Python'}
print(S1 – S2) Changing order we get :
print(S1.difference(S2)) {'Assembly'}
print('Changing order we get: ') {'Assembly'}
print(S2 – S1)
print(S2.difference(S1))
Symmetric Difference: The symmetric difference of two sets A and B is a set that contains
elements in either A or B but not both. “^” operator or symmetric_difference() method in
python is used to perform this operation.
Code Output
S1 = {1, 2, 3} {1, 2, 4, 5}
S2 = {3, 4, 5} {1, 2, 4, 5}
print(S1 ^ S2)
print(S1.symmetric_difference(S2))

Dictionary
A dictionary is like a list, but more in general. In a list, index value is an integer, while in a
dictionary index value can be any other data type and are called keys. The key will be used
as a string as it is easy to recall. A dictionary is an extremely useful data storage construct
for storing and retrieving all key value pairs, where each element is accessed (or indexed)
by a unique key. However, dictionary keys are not in sequences and hence maintain no left-
to right order.
KEY VALUE PAIR: We can refer to a dictionary as a mapping between a set of indices (which
are called keys) and a set of values. Each key maps a value. The association of a key and a
value is called a key-value pair.
Syntax:
my_dict = {'key1': 'value1','key2': 'value2','key3': 'value3'…'keyn': 'valuen'}
Features of dictionary
 Curley brackets are used to represent a dictionary.
 Each pair in the dictionary is represented by a key and value separated by a colon.
 Multiple pairs are separated by comas
 A dictionary is an unordered collection of keyvalue pairs.
 A dictionary has a length, specifically the number of keyvalue pairs.
 A dictionary provides fast look up by key.
 The keys must be immutable object types.
STATE DIAGRAM
>>> A={1:"one",2:"two",3:"three"}

1 one
A= 2 two
3 three

KEYS VALUES
CREATING DICTIONARAY – dict()
The function dict ( ) is used to create a new dictionary with no items. This function is called
built-in function. We can also create dictionary using {}.
Code: >>>computer={'input':'keybord','output':'mouse','language':'python','os':'windo
ws-10'}
>>> print computer
Outpu {'input': 'keyboard', 'os': 'windows-8', 'language': 'python', 'output': 'mouse'}
t
Creating and traversing a dictionary
Code: def dictionary():
H={'Four': 'scanner', 'three': 'printer', 'two': 'Mouse', 'one':
'keyboard'}
for i in H:
print(i,":", H[i])
dictionary()
Output Four : scanner
three : printer
two : Mouse
one : keyboard

BUILT IN METHODS

Dictionary Method Meaning

dict.clear() Removes all the elements of the dictionary

dict.copy() Returns (shallow)copy of dictionary.

dict.get(key, for key key, returns value or default if key not in dictionary
default=None) (note that default's default is None)

dict.items() returns a list of dict's (key, value) tuple pairs

dict.keys() returns list of dictionary dict's keys

dict.setdefault key, similar to get(), but will set dict[key]=default if key is not
default=None already in dict

dict.update(dict2) adds dictionary dict2's key-values pairs to dict

dict.values() returns list of dictionary dict's values


dict.pop() returns list of dictionary dict's keys

dict.popitem() similar to get(), but will set dict[key]=default if key is not


already in dict

Stack
A stack is a linear data structure that stores items in a Last In First Out way. In stack,
elements are added at one end and an element is deleted from that end only. The insert
and delete operations are called push and pop operations.
As an example, the data in the stack is stored in a similar order as dish plates are stacked
one above another on the dining table.

Operations on Stack
Push Operation: Push operation as demonstrated in below diagram will add an element at
the top of stack.
Pop operation: Pop operation as demonstrated in below diagram removes an element from
the top of the stack.

Methods of Python Stack


The functions/methods associated with stacks are listed below:
1. empty() – Returns a boolean (True/False) value as True if the stack is empty
2. size() – Returns size of the stack or number of items/elements stored in the stack
3. top() – Returns a reference to the topmost available element stored in the stack
4. push(a) – Inserts an element at the top of the stack
5. pop() – Deletes the topmost element from the last occupied memory location of the
stack
Stack implementation
Code Output
# Program 1 - Python program to Initial stack with 4 elements one,
demonstrate stack implementation using two, three, four loaded in
the list sequence
['one', 'two', 'three', 'four']
stack_example = [] 3 Elements popped from stack in
LIFO order:
four
# append() function to push element in the three
stack two
stack_example.append('one')
stack_example.append('two') Stack after 3 elements are popped:
stack_example.append('three') ['one']
stack_example.append('four')
Stack is left with one element only
print('Initial stack with 4 elements one, one
two, three, four loaded in sequence') Traceback (most recent call last):
print(stack_example) File "D:/list.py", line 27, in
<module>
# pop() function to pop element from print(stack_example.pop())
stack in LIFO order IndexError: pop from empty list
print('3 Elements popped from stack in
LIFO order:')
print(stack_example.pop())
print(stack_example.pop())
print(stack_example.pop())

print('\nStack after 3 elements are


popped:')
print(stack_example)
# stack is left with one element only

print('\nStack is left with one element


only')
print(stack_example.pop())
print(stack_example.pop())

Queue
Queue in python is one of the linear data structures used to store data in the memory. We
can define a queue as a linear data structure that stores data sequentially based on the First
In First Out (FIFO) manner. So, the data inserted first will be removed from the queue first.
Since the first element inserted is served and removed, the queue data structure is also
known as the First Come First Served data structure.
A linear data structure is a collection of elements such that each element is arranged
sequentially, and each member element is connected to its previous and next elements.
Operations of Queue in Python
Queue in python is one of the most important and commonly used data structures. We can
perform various operations using queues in python. Let us learn about the various
operation associated with queues in python.
1. Enqueue: Inserting an element of data into the queue is known as enqueue. An element
is inserted or enqueued from the rear end of the queue.
If a queue is full, then we cannot insert any new element into the queue. This condition is
known as overflow condition.

2. Dequeue: Deleting or removing an element of data from the queue is known as dequeue.
An element is deleted or dequeued from the front end of the queue. Since the front end is
always maintained, we can directly delete an element from the queue.
If a queue is empty, then we cannot remove any element from the queue. This condition is
known as the underflow condition.
3. Front: The front is a pointer that points to the element first inserted into the queue. The
front of a queue helps us to get the oldest element present in the queue.
4. Rear: The rear is a kind of pointer that points to the element which is last inserted into
the queue. The rear of a queue helps us to get the newest element present in the queue.
Methods Available in Queue
1. put(item): The queue provides the put(item) method in python to insert an element into
the queue. The put(item) method uses the rear pointer to insert an element in the queue.
2. get(): The queue provides the get() method in python to get or extract an element from
the queue. The get() method uses the front pointer to get an element of the queue.
3. empty(): The empty() method is provided by the queue in python to check whether the
queue is empty. The empty() method uses the front pointer and returns a boolean value.
The queue is empty if the empty() method returns true. Else, the queue has some elements
in it.
4. qsize(): The qsize() method is provided by the queue in python to get the size, i.e., the
number of elements present in the queue.
5. full(): The full() method is vice versa of the empty() method. The full() method is provided
by the queue in python to check whether the queue is full or not. The full() method uses
the rear pointer and returns a boolean value. If the full() method returns true, the queue is
filled with no space left.

Implementation of Queue in list


Code Output
[1, 2]
# Initializing a list-based queue 1
queue = [] 2
[]
# Enqueue elements or appending
elements
queue.append(1)
queue.append(2)
print(queue)

# Dequeue elements or popping


elements
print(queue.pop(0))
print(queue.pop(0))

print(queue)
Searching and Sorting
Linear Search: Linear search is a simple search algorithm used to find the position of a
target value within a list. It sequentially checks each element until a match is found or the
list is exhausted.
Linear Search Concept and Example
Suppose a list of elements is given and let's say we want to look for the value 29 in that list.
The list of elements is given below.

Step 1: We take into account the first value, which is 20 from the list, and compare it to our
search value, which is 29. We move on to the following value in the list because it is not
equal.
Step 2: Next, we take into account the second element which is 64, and compare it with our
required value of 0. We proceed to the following element once more because it is not
equal.
Step 3: Now we have 6 as the next element in the list. When we compare the two
elements, we see that 6 is not equivalent to 29. We now go on to the next element.
Step 4: Now have got 29 as our next element. So this 29 is compared to our required 29 and
we have identified the element we were looking for in the list since 29 is equivalent to 29.
The element's index value is 3 now this index value can be returned for use in
further calculations after we print a message indicating that the element has been located
at index 3.
Implementation
Code Output
def search(a, l, x): The given array is [10, 8, 6, 4, 2]
Element to be searched is 6
# Traversing the array Element is at index 2
for i in range(l):
if (a[i] == x):
return i
return -1

a = [10, 8, 6, 4, 2]
print("The given array is ", a)
x=6
print("Element to be searched is ", x)
l = len(a)
ind = search(a, l, x)
if(ind == -1):
print("Element Not Found")
else:
print("Element is at index ", ind)

Sorting
Sorting is to arrange the list in an ascending or descending order. There are three sorting
techniques that can be used to sort the list in ascending or descending order.
These are:
1. Selection sort
2. Bubble sort
3. Insertion sort
1.Selection sort: The basic logic of selection sort is to repeatedly select the smallest
element in the unsorted part of the array and then swap it with the first element of the
unsorted part of the list.
For example, consider the following array

1. Set the first element as minimum.


2. Compare minimum with the second element. If the second element is smaller
than minimum, assign the second element as minimum.
Compare minimum with the third element. Again, if the third element is smaller, then
assign minimum to the third element otherwise do nothing. The process goes on until the
last element.
3. After each iteration, minimum is placed in the front of the unsorted list.

4. For each iteration, indexing starts from the first unsorted element. Step 1 to 3 are
repeated until all the elements are placed at their correct positions.
Code:
# Selection sort in Python

def selectionSort(array, size):

for step in range(size):


min_idx = step

for i in range(step + 1, size):

# to sort in descending order, change > to < in this line


# select the minimum element in each loop
if array[i] < array[min_idx]:
min_idx = i

# put min at the correct position


(array[step], array[min_idx]) = (array[min_idx],
array[step])

data = [-2, 45, 0, 11, -9]


size = len(data)
selectionSort(data, size)
print('Sorted Array in Ascending Order:')
print(data)
Output:
Sorted Array in Ascending Order:
[-9, -2, 0, 11, 45]
2. Bubble sort : Bubble sort is a sorting algorithm that compares two adjacent elements and
swaps them until they are in the intended order.
Working of Bubble Sort
Suppose we are trying to sort the elements in ascending order.
1. First Iteration (Compare and Swap)
1. Starting from the first index, compare the first and the second elements.
2. If the first element is greater than the second element, they are swapped.
3. Now, compare the second and the third elements. Swap them if they are not in
order.
4. The above process goes on until the last element.

2. Remaining Iteration
The same process goes on for the remaining iterations.
After each iteration, the largest element among the unsorted elements is placed at the end.

In each iteration, the comparison takes place up to the last unsorted element.

The array is sorted when all the unsorted elements are placed at their correct positions.
The array is sorted if all elements are kept in the right order
Code:
# Bubble sort in Python

def bubbleSort(array):

# loop to access each array element


for i in range(len(array)):

# loop to compare array elements


for j in range(0, len(array) - i - 1):

# compare two adjacent elements


# change > to < to sort in descending order
if array[j] > array[j + 1]:

# swapping elements if elements


# are not in the intended order
temp = array[j]
array[j] = array[j+1]
array[j+1] = temp

data = [-2, 45, 0, 11, -9]

bubbleSort(data)

print('Sorted Array in Ascending Order:')


print(data)
Output:
Sorted Array in Ascending Order:
[-9, -2, 0, 11, 45]

3.Insertion Sort: insertion sort is similar to selection sort. The difference is that the
insertion sort does not select the smallest element and put it into place; rather it selects the
next element to the right of what was already sorted. Then it slides up each larger element
until it gets to the correct location to insert into the sorted part of the array.
Suppose we need to sort the following array.

Initial array
1. The first element in the array is assumed to be sorted. Take the second element and
store it separately in key.
Compare key with the first element. If the first element is greater than key, then key is
placed in front of first element.

If the first element is greater than key, then key is placed in front of the first element.
2. Now, the first two elements are sorted.

Take the third element and compare it with the elements on the left of it. Placed it
just behind the element smaller than it. If there is no element smaller than it, then
place it at the beginning of the array.
Place 1 at the beginning
3. Similarly, place every unsorted element at its correct position. Place 4 behind 1

Place 4 behind 1
Place 3 behind 1 and the array is sorted
Code:
# Insertion sort in Python

def insertionSort(array):

for step in range(1, len(array)):


key = array[step]
j = step - 1

# Compare key with each element on the left of it until an element smaller
than it is found
# For descending order, change key<array[j] to key>array[j].
while j >= 0 and key < array[j]:
array[j + 1] = array[j]
j=j-1
# Place key at after the element just smaller than it.
array[j + 1] = key

data = [9, 5, 1, 4, 3]
insertionSort(data)
print('Sorted Array in Ascending Order:')
print(data)
Output:
Sorted Array in Ascending Order:
[1, 3, 4, 5, 9]

You might also like