Pythonunit 6
Pythonunit 6
Pythonunit 6
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.
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:
print("tuple1:", tuple1)
print("tuple2:", tuple2)
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)
print("tuple6:", tuple6)
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)
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
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.setdefault key, similar to get(), but will set dict[key]=default if key is not
default=None 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.
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.
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
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
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):
bubbleSort(data)
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):
# 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]