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

INTRODUCTION

Practical No: ________ Date: ________

Aim: Introduction to Python

Theory:

Python is a language with a simple syntax, and a powerful set of libraries. It is an interpreted
language, with a rich programming environment, including a robust debugger and profiler.
While it is easy for beginners to learn, it is widely used in many scientific areas for data
exploration. We cover data types, control flow, object-oriented programming, and graphical
user interface-driven applications. The examples and problems used in this course are drawn
from diverse areas such as text processing, simple graphics creation and image manipulation,
HTML and web programming, and genomics.

Scope & Objective:

1. Learn basic programming constructs –data types, decision structures, control structures
in python.
2. Know how to use libraries for string manipulation and user-defined functions.
3. Learn to use in-built data structures in python – Lists, Tuples, Dictionary and File
handling.
4. Learn the fundamental principles of Object-Oriented Programming.
5. Solve problems through application of OO concepts and using Files/database.

Use Python Shell (using command line) and IDLE


• Interactive development environment.
• To evaluate expression.
• To create a script.

Using IDLE

IDLE is the standard Python development environment. Its name is an acronym of "Integrated
DeveLopment Environment". It works well on both Unix and Windows platforms.

It has a Python shell window, which gives you access to the Python interactive mode. It also
has a file editor that lets you create and edit existing Python source files.

During the following discussion of IDLE's features, instead of passively reading along, you
should start IDLE and try to replicate the screenshots.

Interactive Python shell

When you start up IDLE, a window with an interactive Python shell will pop up:

Gandhinagar Institute of Technology 3150713 PDS


You can type Python code directly into this shell, at the '>>>' prompt. Whenever you enter a
complete code fragment, it will be executed. For instance, typing:

>>> print("hello world")

and pressing ENTER, will cause the following to be displayed:

hello world

Try typing an underscore ( _). Can you see it? On some operating systems, the bottoms of
hanging letters such as 'g' or 'y', as well as underscores, cannot be seen in IDLE. If this is the
case for you, go to Options -> Configure IDLE, and change the size of the default font to 9 or
11. This will fix the problem!

IDLE can also be used as a calculator:

>>> 4+4
8
>>> 8**3
512

Addition (+), subtraction (-), multiplication (*), division (/), modulo (%) and power (**)
operators are built into the Python language. This means you can use them right away. If you
want to use a square root in your calculation, you can either raise something to the power of
0.5 or you can import the math module. Below are two examples of square root calculation:

>>> 16**0.5
4.0
>>> import math
>>> math.sqrt(16)
4.0
Gandhinagar Institute of Technology 3150713 PDS
The math module allows you to do a number of useful operations:

>>> math.log(16, 2)
4.0
>>> math.cos( 0 )
1.0

Note that you only need to execute the import command once after you start IDLE; however,
you will need to execute it again if you restart the shell, as restarting resets everything back to
how it was when you opened IDLE. Creating scripts

1. Save your hello.py program in the ~/LAB/classFolder folder.


2. Open up the terminal program. ...
3. Type cd ~/LAB/classFolder to change directory to your classFolder folder, and hit
Enter.
4. Type chmod a+x hello.py to tell Linux that it is an executable program.
5. Type ./hello.py to run your program!
Program to add two integers.

Take input from user.


number1 = input(" Please Enter the First Number: ")
number2 = input(" Please Enter the second number: ")
# Using arithmetic + Operator to add two numbers
sum = float(number1) + float(number2)
print('The sum of {0} and {1} is {2}'.format(number1, number2, sum))

Exercises:
1. Program to calculate area of a triangle:
a. Given Base and height of the triangle. Take input from user.
b. Given Three sides of a triangle (Make sure that it forms a triangle). Take input
from user.

Gandhinagar Institute of Technology 3150713 PDS


Gandhinagar Institute of Technology 3150713 PDS
DEMOSTRATION THE WORK OF ‘id’ and ‘type’
Practical No: ________ Date: ________

Aim: Demonstrate the working of ‘id’ and ‘type’ functions

Theory:

The id() function returns identity (unique integer) of an object.


The syntax of id() is: id(object)

As we can see the function accepts a single parameter and is used to return the identity of an
object. This identity has to be unique and constant for this object during the lifetime.
Two objects with non-overlapping lifetimes may have the same id() value. If we relate this to
C, then they are actually the memory address, here in Python it is the unique id. This function
is generally used internally in Python.

Examples:

The output is the identity of the object passed. This is random but when running in the
same program, it generates unique and same identity.

Input:
id(1025)
Output: 2698213093488
Output varies with different runs

Input :
id("geek")
Output: 2698213126704

# This program shows various identities


str1 = "geek"
print(id(str1))

str2 = "geek"
print(id(str2))

# This will return True


print(id(str1) == id(str2))

# Use in Lists
list1 = ["aakash", "priya", "abdul"]
print(id(list1[0]))
Gandhinagar Institute of Technology 3150713 PDS
print(id(list1[2]))

# This returns false


print(id(list1[0])==id(list1[2]))

Value from id():

The id() function returns identity of the object. This is an integer which is unique for the given
object and remains constant during its lifetime.

Example:

print('id of 5 =',id(5))
a = 5
print('id of a =',id(a))
b = a
print('id of b =',id(b))
c = 5.0
print('id of c =',id(c))

The ‘type’ function:

Python have a built-in method called as type which generally come in handy while figuring
out the type of variable used in the program in the runtime.

The type function returns the datatype of any arbitrary object. The possible types are listed
in the types module. This is useful for helper functions that can handle several types of
data.

Example : Introducing type

>>> type(1)
<class 'int'>
>>> li = []
>>> type(li)
<class 'list'>
>>> import odbc
>>> type(odbc)
<class 'module'>
>>> import types
>>> type(odbc) == types.ModuleType
True

Type takes anything -- and I mean anything -- and returns its data type. Integers, strings, lists,
dictionaries, tuples, functions, classes, modules, even types are acceptable.
Gandhinagar Institute of Technology 3150713 PDS
• type can take a variable and return its datatype.
• type also works on modules.

You can use the constants in the types module to compare types of objects. This is what the
info function does, as you'll see shortly.

Exercises:
1. Write a output of following code.
# Python id() function example
l1 = [1,2,3,4]
l2 = [1,2,3,4]
l3 = [3,5,6,7]
# Calling function
id1 = id(l1)
id2 = id(l2)
id3 = id(l3)
# Displaying result
print((l1==l2),(l1==l3))
# Objects with the same values can have different ids
print((id1==id2),(id1==id3))
# l1 and l2 returns True, while id1 and id2 returns False

Review Questions:
1. What data types are used in Python?
2. What is the difference between functions used in python and C? Are both the same?

Gandhinagar Institute of Technology 3150713 PDS


Gandhinagar Institute of Technology 3150713 PDS
PRIME NO USING PYTHON
Practical No: ________ Date: ________

Aim: To find all prime numbers within a given range.

Theory:

Prime numbers: A prime number is a natural number greater than 1 and having no positive
divisor other than 1 and itself.

For example: 3, 7, 11 etc are prime numbers.

Composite number: Other natural numbers that are not prime numbers are called composite
numbers.

For example: 4, 6, 9 etc. are composite numbers.

Here is source code of the Python Program to check if a number is a prime number.

r = int(input("Enter upper limit: "))


for a in range(2,r+1):
k=0
for i in range(2,a//2+1):
if(a%i==0):
k= k+1
if(k<=0):
print(a)

Exercises:
1. Write a python program for composite numbers.

Review Questions:
1. Why don’t we use semi colon in this program?
2. What are Composite numbers?

Gandhinagar Institute of Technology 3150713 PDS


Gandhinagar Institute of Technology 3150713 PDS
FIBONACCI SERIES USING PYTHON
Practical No: ________ Date: ________

Aim: To print ‘n terms of Fibonacci series using iteration.

Theory:

The Fibonacci numbers are the numbers in the following integer sequence. 0, 1, 1, 2, 3, 5, 8, 13,
21, 34, 55, 89, 144, ……..
A Fibonacci sequence is the integer sequence of 0, 1, 1, 2, 3, 5, 8.... The first two terms are 0
and 1. All other terms are obtained by adding the preceding two terms. This means to say the
nth term is the sum of (n-1)th and (n-2)th term. In mathematical terms, the sequence Fn of
Fibonacci numbers is defined by the recurrence relation
Fn = Fn-1 + Fn-2 with initial value F0 = 0 and F1 = 1

# Program to display the Fibonacci sequence up to nth term where n is provided


by the user
# change this value for a different result
nterms = 10
# uncomment following to take input from the user
# nterms = int(input("How many terms? "))

# first two terms


n1 = 0
n2 = 1
count = 0

# check if the number of terms is valid


if nterms <= 0:
print("Please enter a positive integer")
elif nterms == 1:
print("Fibonacci sequence upto",nterms,":")
print(n1)
else:
print("Fibonacci sequence upto",nterms,":")
while count < nterms:
print(n1)

nth = n1 + n2
# update values
n1 = n2
n2 = nth
count += 1

Review Questions:
1. What is the difference between iteration and recursion?
2. How looping technique is different from Recursion?

Gandhinagar Institute of Technology 3150713 PDS


Gandhinagar Institute of Technology 3150713 PDS
DEMOSTRATE USE OF SLICING
Practical No: ________ Date: ________

Aim: To demonstrate use of slicing in string.

Theory:

Like other programming languages, it’s possible to access individual characters of a string by
using array-like indexing syntax. In this we can access each and every element of string through
their index number and the indexing starts from 0. Python does index out of bound checking.

So, we can obtain the required character using syntax, string_name[index_position]:


The positive index_position denotes the element from the starting(0) and the negative
index shows the index from the end(-1).

Example:

# A python program to illustrate slicing in strings


x = "Gandhinagar Institute of Technology"

# Prints 3rd character beginning from 0


print(x[2])

# Prints 7th character


print(x[6])

# Prints 3rd character from rear beginning from 1


print(x[-3])

# Length of string is 10 so it is out of bound


print(x[15])

We use the slice notation on strings. In this example, we omit the first index to start at the
beginning, and then consume four characters total. We extract the first four letters.

Python program that slices string

word = "something"

# Get first four characters.


part = word[:4]
print(part)

Copy with slicing, we can copy sequences like lists. We assign a new list variable to a slice
with no specified start or stop values. So the slice copies the entire list and returns it.

To extract substring from the whole string then we use the syntax like

Gandhinagar Institute of Technology 3150713 PDS


string_name[beginning: end : step]

end denotes the end index of string which is not inclusive, steps denote the distance between
the two words. o beginning represents the starting index of string

Exercises:
1. Accept a string from the user and display the string with first character of each word
Capital. (Without using inbuilt function)
2. Write a program to accept a string from the user and display n characters from the left
of the string. (Accept n from the user)
3. Write a program to reverse the string using slicing.
4. Write a program to accept a string from the user and display n characters from the
right of the string. (Accept n from the user)
5. Accept a String from the user and display first two characters of each word in same
line separated by space.

Review Questions:

1. Are Strings immutable? Explain.


2. What are the ways to create a string?
3. Write the output of the following code
str = “Welcome to my blog”
a. print( str [3 : 18]
b. print ( str[ 2 : 14 : 2])
c. print( str [ : 8 ])
d. print( str[8 : -1 : 1])
e. print(str [-9 : -15])
f. print(str[0 : 9 : 3])
g. print(str[9 : 29 : 2])
h. print(str[-6 : -9 : -3])
i. print(str[-9 : -9 : -1])
j. print(str[8 : 25 : 3])
4. Write the output of the following: str = “String Slicing in Python”
a. print(str [13 : 18])
b. print(str[ -2 : -4 : -2])
c. print(str [12 : 18 : 2])
d. print(str[-17 : -1 : 1])
e. print(str[-6 : -20 : -2])
f. print(str[0 : 9 : 3])
g. print(str[19 : 29])
h. print(str[-6 : -9 : -3])
i. print(str[-9 : -0 : -1])
j. print(str[2 : 16 : 3])

Gandhinagar Institute of Technology 3150713 PDS


STRING MANIPLULATION
Practical No: ________ Date: ________

Aim: Manipulate the string as per the requirement.

Theory:

To add 'ing' at the end of a given string (length should be at least 3). If the given string already
ends with 'ing' then add 'ly' instead. If the string length of the given string is less than 3, leave
it unchanged.

Sample String: 'abc'


Expected Result: 'abcing'

Sample String: 'string'


Expected Result: 'stringly'

To get a string from a given string where all occurrences of its first char have been changed
to '$', except the first char itself.

Sample String : 'restart'


Expected Result : 'resta$t'

Python Code:

def add_string(str1):
length = len(str1)
if length > 2:
if str1[-3:] == 'ing':
str1 += 'ly'
else:
str1 += 'ing'
return str1

print(add_string('ab'))
print(add_string('abc'))
print(add_string('string'))

b. PYTHON CODE:

def change_char(str1):
char = str1[0]
length = len(str1)
str1 = str1.replace(char, '$')
str1 = char + str1[1:]
return str1
print(change_char('restart'))

Gandhinagar Institute of Technology 3150713 PDS


Exercises:
1. Given a string of odd length greater than 7, return a new string made of the middle
three characters of a given String
2. Given two strings, s1 and s2, create a new string by appending s2 in the middle of s1
3. Arrange string characters such that lowercase letters should come first. [Given an
input string with the combination of the lower and upper case arrange characters in
such a way that all lowercase letters should come first.]
4. Count all lower case, upper case, digits, and special symbols from a given string.
5. String characters balance Test. [We’ll assume that a String s1 and s2 is balanced if all
the chars in the s1 are there in s2. characters’ position doesn’t matter.]
6. Given a string, return the sum and average of the digits that appear in the string,
ignoring all other characters

Review Questions:
1. What are the built-in type does python provides?
2. In Python what are iterators?

Gandhinagar Institute of Technology 3150713 PDS


STRING OPERATION USING PYTHON
Practical No: ________ Date: ________

Aim: To compute the input. The frequency of the words from the output should output after
sorting the key alphanumerically.

Theory:

Introduction to String Operators in Python


In python, String operators represent the different types of operations that can be employed on
the program’s string type of variables. Python allows several string operators that can be
applied on the python string are as below:

• Assignment operator: “=.”


• Concatenate operator: “+.”
• String repetition operator: “*.”
• String slicing operator: “[]”
• String comparison operator: “==” & “!=”
• Membership operator: “in” & “not in”
• Escape sequence operator: “\.”
• String formatting operator: “%” & “{}”

Examples of String Operators in Python


In the following article, we will learn how to perform operations on a string in Python, with
examples.

Example #1 – Assignment Operator “=.”


Python string can be assigned to any variable with an assignment operator “= “. Python string
can be defined with either single quotes [‘ ’], double quotes[“ ”] or triple quotes[‘’’ ‘’’].
var_name = “string” assigns “string” to variable var_name.

Code:
string1 = "hello"
string2 = 'hello'
string3 = '''hello'''
print(string1)
print(string2)
print(string3)

Output:

Example #2 – Concatenate Operator “+.”


Two strings can be concatenated or join using the “+” operator in python, as explained in the
below example code:
Gandhinagar Institute of Technology 3150713 PDS
Code:
string1 = "hello"
string2 = "world "
string_combined = string1+string2
print(string_combined)

Output:

Example #3 – String Repetition Operator “*.”


The same string can be repeated in python by n times using string*n, as explained in the below
example.

Code:
string1 = "helloworld "
print(string1*2)
print(string1*3)
print(string1*4)
print(string1*5)

Output:

Example #4 – String slicing operator “[]”


Characters from a specific index of the string can be accessed with the string[index] operator.
The index is interpreted as a positive index starting from 0 from the left side and a negative
index starting from -1 from the right side.

String H E L L O W O R L D

Positive index 0 1 2 3 4 5 6 7 8 9

Negative index -10 -9 -8 -7 -6 -5 -4 -3 -2 -1

• string[a]: Returns a character from a positive index a of the string from the left side as
displayed in the index graph above.
• string[-a]: Returns a character from a negative index a of the string from the right
side as displayed in the index graph above.
• string[a:b]: Returns characters from positive index a to positive index b of the as
displayed in index graph above.
• string[a:-b]: Returns characters from positive index a to the negative index b of the
string as displayed in the index graph above.
Gandhinagar Institute of Technology 3150713 PDS
• string[a:]: Returns characters from positive index a to the end of the string.
• string[:b] Returns characters from the start of the string to the positive index b.
• string[-a:]: Returns characters from negative index a to the end of the string.
• string[:-b]: Returns characters from the start of the string to the negative index b.
• string[::-1]: Returns a string with reverse order.

Code:
string1 = "helloworld"
print(string1[1])
print(string1[-3])
print(string1[1:5])
print(string1[1:-3])
print(string1[2:])
print(string1[:5])
print(string1[:-2])
print(string1[-2:])
print(string1[::-1])

Output:

Example #5 – String Comparison Operator “==” & “!=”


The string comparison operator in python is used to compare two strings.

• “==” operator returns Boolean True if two strings are the same and return Boolean False
if two strings are not the same.
• “!=” operator returns Boolean True if two strings are not the same and return Boolean
False if two strings are the same.

These operators are mainly used along with if condition to compare two strings where the
decision is to be taken based on string comparison.

Code:
string1 = "hello"
string2 = "hello, world"
string3 = "hello, world"
string4 = "world"
print(string1==string4)
print(string2==string3)
print(string1!=string4)
print(string2!=string3)

Gandhinagar Institute of Technology 3150713 PDS


Output:

Example #6 – Membership Operator “in” & “not in”


Membership operator is used to searching whether the specific character is part/member of a
given input python string.

• “a” in the string: Returns boolean True if “a” is in the string and returns False if “a” is
not in the string.
• “a” not in the string: Returns boolean True if “a” is not in the string and returns False
if “a” is in the string.

A membership operator is also useful to find whether a specific substring is part of a given
string.

Code:
string1 = "helloworld"
print("w" in string1)
print("W" in string1)
print("t" in string1)
print("t" not in string1)
print("hello" in string1)
print("Hello" in string1)
print("hello" not in string1)

Output:

Example #7 – Escape Sequence Operator “\.”


To insert a non-allowed character in the given input string, an escape character is used. An
escape character is a “\” or “backslash” operator followed by a non-allowed character. An
example of a non-allowed character in python string is inserting double quotes in the string
surrounded by double-quotes.

1. Example of non-allowed double quotes in python string:


Code:
string = "Hello world I am from "India""
print(string)

Gandhinagar Institute of Technology 3150713 PDS


Output:

2. Example of non-allowed double quotes with escape sequence operator:

Code:
string = "Hello world I am from \"India\""
print(string)

Output:

Example #8 – String Formatting Operator “%.”


String formatting operator is used to format a string as per requirement. To insert another type
of variable along with string, the “%” operator is used along with python string. “%” is prefixed
to another character indicating the type of value we want to insert along with the python string.
Please refer to the below table for some of the commonly used different string formatting
specifiers:

Operator Description

%d Signed decimal integer

%u unsigned decimal integer

%c Character

%s String

%f Floating-point real number

Code:
name = "india"
age = 19
marks = 20.56
string1 = 'Hey %s' % (name)
print(string1)
string2 = 'my age is %d' % (age)
print(string2)
string3= 'Hey %s, my age is %d' % (name, age)
print(string3)
Gandhinagar Institute of Technology 3150713 PDS
string3= 'Hey %s, my subject mark is %f' % (name, marks)
print(string3)
Output:

Exercises:
1. Write a python program to get the input from user console and find the frequency of
words in input and print in sorted order.
2. Write a program that accepts a comma separated sequence of words as input and
prints the words in a comma-separated sequence after sorting them alphabetically.

Review Questions:
1. Define string operations.
2. What is concatenation function?

Gandhinagar Institute of Technology 3150713 PDS


LIST FUNCTIONS AND OPERATION
Practical No: ________ Date: ________

Aim: To demonstrate use of list their functions and operation

Theory: Python has a number of built-in data structures, including lists. Data structures provide
us with a way to organize and store data, and we can use built-in methods to retrieve or
manipulate that data.

Python List index()


The index() method returns the index of the specified element in the list.
The syntax of the list index() method is:

list.index(element, start, end)

list index() parameters


The list index() method can take a maximum of three arguments:
• element - the element to be searched
• start (optional) - start searching from this index
• end (optional) - search the element up to this index

Return Value from List index()


• The index() method returns the index of the given element in the list.
• If the element is not found, a ValueError exception is raised.
• The index() method only returns the first occurrence of the matching element.

Example 1: Find the index of the element

# vowels list
vowels = ['a', 'e', 'i', 'o', 'i', 'u']

# index of 'e' in vowels


index = vowels.index('e')
print('The index of e:', index)

# element 'i' is searched


# index of the first 'i' is returned
index = vowels.index('i')

print('The index of i:', index)

Output:
The index of e: 1
The index of i: 2

Example 2: Index of the Element not Present in the List


# vowels list
vowels = ['a', 'e', 'i', 'o', 'u']

Gandhinagar Institute of Technology 3150713 PDS


# index of'p' is vowels
index = vowels.index('p')
print('The index of p:', index)
Output
ValueError: 'p' is not in list

Example 3: Working of index() With Start and End Parameters


# alphabets list
alphabets = ['a', 'e', 'i', 'o', 'g', 'l', 'i', 'u']

# index of 'i' in alphabets


index = alphabets.index('e') # 1
print('The index of e:', index)

# 'i' after the 4th index is searched


index = alphabets.index('i', 4) # 6
print('The index of i:', index)

# 'i' between 3rd and 5th index is searched


index = alphabets.index('i', 3, 5) # Error!
print('The index of i:', index)

Output:
The index of e: 1
The index of i: 6
Traceback (most recent call last):
File "*lt;string>", line 13, in
ValueError: 'i' is not in list

Python List append()


The append() method adds an item to the end of the list.
The syntax of the append() method is:
list.append(item)

append() Parameters

The method takes a single argument


• item - an item to be added at the end of the list
The item can be numbers, strings, dictionaries, another list, and so on.

Return Value from append()


The method doesn't return any value (returns None).

Example 1: Adding Element to a List


# animals list
animals = ['cat', 'dog', 'rabbit']

# 'guinea pig' is appended to the animals list


Gandhinagar Institute of Technology 3150713 PDS
animals.append('guinea pig')

# Updated animals list


print('Updated animals list: ', animals)

Output
Updated animals list: ['cat', 'dog', 'rabbit', 'guinea pig']

Example 2: Adding List to a List


# animals list
animals = ['cat', 'dog', 'rabbit']

# list of wild animals


wild_animals = ['tiger', 'fox']

# appending wild_animals list to the animals list


animals.append(wild_animals)

print('Updated animals list: ', animals)

Output
Updated animals list: ['cat', 'dog', 'rabbit', ['tiger', 'fox']]

It is important to notice that, a single item (wild_animals list) is added to the animals list in
the above program.
If you need to add items of a list to another list (rather than the list itself), use the extend()
method.

Python List extend()


The extend() method adds all the elements of an iterable (list, tuple, string etc.) to the end of
the list.
The syntax of the extend() method is:
list1.extend(iterable)

Here, all the elements of iterable are added to the end of list1.

extend() Parameters
As mentioned, the extend() method takes an iterable such as list, tuple, string etc.

Return Value from extend()


The extend() method modifies the original list. It doesn't return any value.

Example 1: Using extend() Method


# languages list
languages = ['French', 'English']

# another list of language


languages1 = ['Spanish', 'Portuguese']

Gandhinagar Institute of Technology 3150713 PDS


# appending language1 elements to language
languages.extend(languages1)

print('Languages List:', languages)


Output
Languages List: ['French', 'English', 'Spanish', 'Portuguese']

Example 2: Add Elements of Tuple and Set to List


# languages list
languages = ['French']

# languages tuple
languages_tuple = ('Spanish', 'Portuguese')

# languages set
languages_set = {'Chinese', 'Japanese'}

# appending language_tuple elements to language


languages.extend(languages_tuple)

print('New Language List:', languages)

# appending language_set elements to language


languages.extend(languages_set)

print('Newer Languages List:', languages)


Output
New Languages List: ['French', 'Spanish', 'Portuguese']
Newer Languages List: ['French', 'Spanish', 'Portuguese', 'Japanese', 'Chinese']

Other Ways to Extend a List


You can also append all elements of an iterable to the list using:
1. the + operator

a = [1, 2]
b = [3, 4]

a += b # a = a + b

# Output: [1, 2, 3, 4]
print('a =', a)
Output
a = [1, 2, 3, 4]

2. the list slicing syntax


a = [1, 2]
b = [3, 4]

Gandhinagar Institute of Technology 3150713 PDS


a[len(a):] = b

# Output: [1, 2, 3, 4]
print('a =', a)
Output
a = [1, 2, 3, 4]

Python extend() Vs append()


If you need to add an element to the end of a list, you can use the append() method.
a1 = [1, 2]
a2 = [1, 2]
b = (3, 4)

# a1 = [1, 2, 3, 4]
a1.extend(b)
print(a1)

# a2 = [1, 2, (3, 4)]


a2.append(b)
print(a2)
Output
[1, 2, 3, 4]
[1, 2, (3, 4)]

Python List insert()


The list insert() method inserts an element to the list at the specified index.
The syntax of the insert() method is
list.insert(i, elem)

Here, elem is inserted to the list at the ith index. All the elements after elem are shifted to the
right.

insert() Parameters
The insert() method takes two parameters:
index - the index where the element needs to be inserted
element - this is the element to be inserted in the list
Notes:
If index is 0, the element is inserted at the beginning of the list.
If index is 3, the index of the inserted element will be 3 (4th element in the list).

Return Value from insert()


The insert() method doesn't return anything; returns None. It only updates the current list.

Example 1: Inserting an Element to the List


# vowel list
vowel = ['a', 'e', 'i', 'u']

# 'o' is inserted at index 3 (4th position)


Gandhinagar Institute of Technology 3150713 PDS
vowel.insert(3, 'o')

print('Updated List:', vowel)


Output
Updated List: ['a', 'e', 'i', 'o', 'u']

Example 2: Inserting a Tuple (as an Element) to the List


mixed_list = [{1, 2}, [5, 6, 7]]

# number tuple
number_tuple = (3, 4)

# inserting a tuple to the list


mixed_list.insert(1, number_tuple)

print('Updated List:', mixed_list)


Output
Updated List: [{1, 2}, (3, 4), [5, 6, 7]]

Python List remove()


The remove() method removes the first matching element (which is passed as an argument)
from the list.
The syntax of the remove() method is:
list.remove(element)

remove() Parameters
The remove() method takes a single element as an argument and removes it from the list.
If the element doesn't exist, it throws ValueError: list.remove(x): x not in list exception.

Return Value from remove()


The remove() doesn't return any value (returns None).

Example 1: Remove element from the list


# animals list
animals = ['cat', 'dog', 'rabbit', 'guinea pig']

# 'rabbit' is removed
animals.remove('rabbit')

# Updated animals List


print('Updated animals list: ', animals)
Output
Updated animals list: ['cat', 'dog', 'guinea pig']

Example 2: remove() method on a list having duplicate elements


If a list contains duplicate elements, the remove() method only removes the first matching
element.
# animals list

Gandhinagar Institute of Technology 3150713 PDS


animals = ['cat', 'dog', 'dog', 'guinea pig', 'dog']

# 'dog' is removed
animals.remove('dog')

# Updated animals list


print('Updated animals list: ', animals)
Output
Updated animals list: [‘cat’, ‘dog’, ‘guinea pig’, ‘dog’]

Here, only the first occurrence of element 'dog' is removed from the list.

Example 3: Deleting element that doesn't exist


# animals list
animals = ['cat', 'dog', 'rabbit', 'guinea pig']

# Deleting 'fish' element


animals.remove('fish')

# Updated animals List


print('Updated animals list: ', animals)
Output
Traceback (most recent call last):
File ".. .. ..", line 5, in <module>
animal.remove('fish')
ValueError: list.remove(x): x not in list
Here, we are getting an error because the animals list doesn't contain 'fish'.
• If you need to delete elements based on the index (like the fourth element), you can
use the pop() method.
• Also, you can use the Python del statement to remove items from the list.

Python List count()


The count() method returns the number of times the specified element appears in the list.
The syntax of the count() method is:
list.count(element)

count() Parameters
The count() method takes a single argument:
element - the element to be counted

Return value from count()


The count() method returns the number of times element appears in the list.

Example 1: Use of count()


# vowels list
vowels = ['a', 'e', 'i', 'o', 'i', 'u']

# count element 'i'

Gandhinagar Institute of Technology 3150713 PDS


count = vowels.count('i')

# print count
print('The count of i is:', count)

# count element 'p'


count = vowels.count('p')

# print count
print('The count of p is:', count)
Output
The count of i is: 2
The count of p is: 0

Example 2: Count Tuple and List Elements Inside List


# random list
random = ['a', ('a', 'b'), ('a', 'b'), [3, 4]]

# count element ('a', 'b')


count = random.count(('a', 'b'))

# print count
print("The count of ('a', 'b') is:", count)

# count element [3, 4]


count = random.count([3, 4])

# print count
print("The count of [3, 4] is:", count)

Output
The count of ('a', 'b') is: 2
The count of [3, 4] is: 1

Python List pop()


The pop() method removes the item at the given index from the list and returns the removed
item.
The syntax of the pop() method is:
list.pop(index)

pop() parameters
• The pop() method takes a single argument (index).
• The argument passed to the method is optional. If not passed, the default index -1 is
passed as an argument (index of the last item).
• If the index passed to the method is not in range, it throws IndexError: pop index
out of range exception.

Return Value from pop()

Gandhinagar Institute of Technology 3150713 PDS


The pop() method returns the item present at the given index. This item is also removed from
the list.

Example 1: Pop item at the given index from the list


# programming languages list
languages = ['Python', 'Java', 'C++', 'French', 'C']

# remove and return the 4th item


return_value = languages.pop(3)
print('Return Value:', return_value)

# Updated List
print('Updated List:', languages)
Output
Return Value: French
Updated List: ['Python', 'Java', 'C++', 'C']

Note: Index in Python starts from 0, not 1.

If you need to pop the 4th element, you need to pass 3 to the pop() method.

Example 2: pop() without an index, and for negative indices


# programming languages list
languages = ['Python', 'Java', 'C++', 'Ruby', 'C']

# remove and return the last item


print('When index is not passed:')
print('Return Value:', languages.pop())
print('Updated List:', languages)

# remove and return the last item


print('\nWhen -1 is passed:')
print('Return Value:', languages.pop(-1))
print('Updated List:', languages)

# remove and return the third last item


print('\nWhen -3 is passed:')
print('Return Value:', languages.pop(-3))
print('Updated List:', languages)
Output
When index is not passed:
Return Value: C
Updated List: ['Python', 'Java', 'C++', 'Ruby']

When -1 is passed:
Return Value: Ruby
Updated List: ['Python', 'Java', 'C++']
Gandhinagar Institute of Technology 3150713 PDS
When -3 is passed:
Return Value: Python
Updated List: ['Java', 'C++']

If you need to remove the given item from the list, you can to use the remove() method.
And, you can use the del statement to remove an item or slices from the list.

Python List reverse()


The reverse() method reverses the elements of the list.
The syntax of the reverse() method is:
list.reverse()

reverse() parameter
The reverse() method doesn't take any arguments.

Return Value from reverse()


The reverse() method doesn't return any value. It updates the existing list.

Example 1: Reverse a List


# Operating System List
systems = ['Windows', 'macOS', 'Linux']
print('Original List:', systems)

# List Reverse
systems.reverse()

# updated list
print('Updated List:', systems)
Output
Original List: ['Windows', 'macOS', 'Linux']
Updated List: ['Linux', 'macOS', 'Windows']

There are other several ways to reverse a list.

Example 2: Reverse a List Using Slicing Operator


# Operating System List
systems = ['Windows', 'macOS', 'Linux']
print('Original List:', systems)

# Reversing a list
#Syntax: reversed_list = systems[start:stop:step]
reversed_list = systems[::-1]

# updated list
print('Updated List:', reversed_list)
Output
Gandhinagar Institute of Technology 3150713 PDS
Original List: ['Windows', 'macOS', 'Linux']
Updated List: ['Linux', 'macOS', 'Windows']

Example 3: Accessing Elements in Reversed Order


If you need to access individual elements of a list in the reverse order, it's better to
use reversed() function.
# Operating System List
systems = ['Windows', 'macOS', 'Linux']

# Printing Elements in Reversed Order


for o in reversed(systems):
print(o)
Output
Linux
macOS
Windows

Python List sort()


The sort() method sorts the elements of a given list in a specific ascending or descending
order.
The syntax of the sort() method is:
list.sort(key=..., reverse=...)

Alternatively, you can also use Python's built-in sorted() function for the same purpose.
sorted(list, key=..., reverse=...)

Note: The simplest difference between sort() and sorted() is: sort() changes the list directly
and doesn't return any value, while sorted() doesn't change the list and returns the sorted list.

sort() Parameters
By default, sort() doesn't require any extra parameters. However, it has two optional
parameters:
• reverse - If True, the sorted list is reversed (or sorted in Descending order)
• key - function that serves as a key for the sort comparison

Return value from sort()


The sort() method doesn't return any value. Rather, it changes the original list.
If you want a function to return the sorted list rather than change the original list,
use sorted().

Example 1: Sort a given list


# vowels list
vowels = ['e', 'a', 'u', 'o', 'i']

# sort the vowels


vowels.sort()

# print vowels

Gandhinagar Institute of Technology 3150713 PDS


print('Sorted list:', vowels)

Output
Sorted list: ['a', 'e', 'i', 'o', 'u']

Sort in Descending order


The sort() method accepts a reverse parameter as an optional argument.
Setting reverse = True sorts the list in the descending order.
list.sort(reverse=True)
Alternately for sorted(), you can use the following code.
sorted(list, reverse=True)

Example 2: Sort the list in Descending order


# vowels list
vowels = ['e', 'a', 'u', 'o', 'i']

# sort the vowels


vowels.sort(reverse=True)

# print vowels
print('Sorted list (in Descending):', vowels)
Output
Sorted list (in Descending): ['u', 'o', 'i', 'e', 'a']

Sort with custom function using key


If you want your own implementation for sorting, the sort() method also accepts
a key function as an optional parameter.
Based on the results of the key function, you can sort the given list.
list.sort(key=len)
Alternatively for sorted:

sorted(list, key=len)
Here, len is the Python's in-built function to count the length of an element.
The list is sorted based on the length of each element, from lowest count to highest.

We know that a tuple is sorted using its first parameter by default. Let's look at how to
customize the sort() method to sort using the second element.

Example 3: Sort the list using key


# take second element for sort
def takeSecond(elem):
return elem[1]

# random list
random = [(2, 2), (3, 4), (4, 1), (1, 3)]

# sort list with key


random.sort(key=takeSecond)

Gandhinagar Institute of Technology 3150713 PDS


# print list
print('Sorted list:', random)
Output
Sorted list: [(4, 1), (2, 2), (1, 3), (3, 4)]

Let's take another example. Suppose we have a list of information about the employees of an
office where each element is a dictionary.
We can sort the list in the following way:
# sorting using custom key
employees = [
{'Name': 'Alan Turing', 'age': 25, 'salary': 10000},
{'Name': 'Sharon Lin', 'age': 30, 'salary': 8000},
{'Name': 'John Hopkins', 'age': 18, 'salary': 1000},
{'Name': 'Mikhail Tal', 'age': 40, 'salary': 15000},
]

# custom functions to get employee info


def get_name(employee):
return employee.get('Name')

def get_age(employee):
return employee.get('age')

def get_salary(employee):
return employee.get('salary')

# sort by name (Ascending order)


employees.sort(key=get_name)
print(employees, end='\n\n')

# sort by Age (Ascending order)


employees.sort(key=get_age)
print(employees, end='\n\n')

# sort by salary (Descending order)


employees.sort(key=get_salary, reverse=True)
print(employees, end='\n\n')
Output
[{'Name': 'Alan Turing', 'age': 25, 'salary': 10000}, {'Name': 'John Hopkins', 'age': 18, 'salary':
1000}, {'Name': 'Mikhail Tal', 'age': 40, 'salary': 15000}, {'Name': 'Sharon Lin', 'age': 30,
'salary': 8000}]

[{'Name': 'John Hopkins', 'age': 18, 'salary': 1000}, {'Name': 'Alan Turing', 'age': 25, 'salary':
10000}, {'Name': 'Sharon Lin', 'age': 30, 'salary': 8000}, {'Name': 'Mikhail Tal', 'age': 40,
'salary': 15000}]

Gandhinagar Institute of Technology 3150713 PDS


[{'Name': 'Mikhail Tal', 'age': 40, 'salary': 15000}, {'Name': 'Alan Turing', 'age': 25, 'salary':
10000}, {'Name': 'Sharon Lin', 'age': 30, 'salary': 8000}, {'Name': 'John Hopkins', 'age': 18,
'salary': 1000}]
Here, for the first case, our custom function returns the name of each employee. Since the name
is a string, Python by default sorts it using the alphabetical order.

For the second case, age (int) is returned and is sorted in ascending order.

For the third case, the function returns the salary (int), and is sorted in the descending order
using reverse = True.

It is a good practice to use the lambda function when the function can be summarized in one
line. So, we can also write the above program as:
# sorting using custom key
employees = [
{'Name': 'Alan Turing', 'age': 25, 'salary': 10000},
{'Name': 'Sharon Lin', 'age': 30, 'salary': 8000},
{'Name': 'John Hopkins', 'age': 18, 'salary': 1000},
{'Name': 'Mikhail Tal', 'age': 40, 'salary': 15000},
]

# sort by name (Ascending order)


employees.sort(key=lambda x: x.get('Name'))
print(employees, end='\n\n')

# sort by Age (Ascending order)


employees.sort(key=lambda x: x.get('age'))
print(employees, end='\n\n')

# sort by salary (Descending order)


employees.sort(key=lambda x: x.get('salary'), reverse=True)
print(employees, end='\n\n')
Output
[{'Name': 'Alan Turing', 'age': 25, 'salary': 10000}, {'Name': 'John Hopkins', 'age': 18, 'salary':
1000}, {'Name': 'Mikhail Tal', 'age': 40, 'salary': 15000}, {'Name': 'Sharon Lin', 'age': 30,
'salary': 8000}]

[{'Name': 'John Hopkins', 'age': 18, 'salary': 1000}, {'Name': 'Alan Turing', 'age': 25, 'salary':
10000}, {'Name': 'Sharon Lin', 'age': 30, 'salary': 8000}, {'Name': 'Mikhail Tal', 'age': 40,
'salary': 15000}]

[{'Name': 'Mikhail Tal', 'age': 40, 'salary': 15000}, {'Name': 'Alan Turing', 'age': 25, 'salary':
10000}, {'Name': 'Sharon Lin', 'age': 30, 'salary': 8000}, {'Name': 'John Hopkins', 'age': 18,
'salary': 1000}]

Python List copy()


The copy() method returns a shallow copy of the list.
A list can be copied using the = operator.

Gandhinagar Institute of Technology 3150713 PDS


For example,
old_list = [1, 2, 3]
new_list = old_list

The problem with copying lists in this way is that if you modify new_list, old_list is also
modified. It is because the new list is referencing or pointing to the same old_list object.

old_list = [1, 2, 3]
new_list = old_list

# add an element to list


new_list.append('a')

print('New List:', new_list)


print('Old List:', old_list)
Output
Old List: [1, 2, 3, 'a']
New List: [1, 2, 3, 'a']

However, if you need the original list unchanged when the new list is modified, you can use
the copy() method.

The syntax of the copy() method is:


new_list = list.copy()

copy() parameters
The copy() method doesn't take any parameters.
Return Value from copy()
The copy() method returns a new list. It doesn't modify the original list.

Example 1: Copying a List


# mixed list
my_list = ['cat', 0, 6.7]

# copying a list
new_list = my_list.copy()

print('Copied List:', new_list)

Output
Copied List: ['cat', 0, 6.7]

If you modify the new_list in the above example, my_list will not be modified.

Example 2: Copy List Using Slicing Syntax


# shallow copy using the slicing syntax

Gandhinagar Institute of Technology 3150713 PDS


# mixed list
list = ['cat', 0, 6.7]

# copying a list using slicing


new_list = list[:]

# Adding an element to the new list


new_list.append('dog')

# Printing new and old list


print('Old List:', list)
print('New List:', new_list)

Output
Old List: ['cat', 0, 6.7]
New List: ['cat', 0, 6.7, 'dog']

Python List clear()


The clear() method removes all items from the list.
The syntax of clear() method is:
list.clear()

clear() Parameters
The clear() method doesn't take any parameters.

Return Value from clear()


The clear() method only empties the given list. It doesn't return any value.

Example 1: Working of clear() method


# Defining a list
list = [{1, 2}, ('a'), ['1.1', '2.2']]

# clearing the list


list.clear()

print('List:', list)
Output
List: []

Note: If you are using Python 2 or Python 3.2 and below, you cannot use the clear() method.
You can use the del operator instead.

Example 2: Emptying the List Using del


# Defining a list
list = [{1, 2}, ('a'), ['1.1', '2.2']]

# clearing the list


del list[:]

Gandhinagar Institute of Technology 3150713 PDS


print('List:', list)
Output
List: []

Exercises:
1. Concatenate two lists index-wise.
2. Given a Python list of numbers. Turn every item of a list into its square
3. Remove empty strings from the list of strings.
4. Given a nested list extend it by adding the sub list ["h", "i", "j"] in such a way that it
will look like the following list.
list1 = ["a", "b", ["c", ["d", "e", ["f", "g"], "k"], "l"], "m", "n"]
Expected List:
list1= ['a', 'b', ['c', ['d', 'e', ['f', 'g', 'h', 'i', 'j'], 'k'], 'l'], 'm', 'n']

5. Given a Python list, find value 20 in the list, and if it is present, replace it with 200.
Only update the first occurrence of a value.
list1 = [5, 10, 15, 20, 25, 50, 20]
6. Given a Python list, remove all occurrence of 20 from the list.
list1 = [5, 10, 15, 20, 25, 50, 20]

Review Questions:
1. How do you remove duplicates froma list?
2. How To Determine The Size Of Your List in Python?

Gandhinagar Institute of Technology 3150713 PDS


Gandhinagar Institute of Technology 3150713 PDS
Gandhinagar Institute of Technology 3150713 PDS
TUPLE AND THEIR FUNCTIONS
Practical No: ________ Date: _________

Aim: To demonstrate use of tuple and their functions

Theory: In Python programming, a tuple is similar to a list. The differences between the two
is that we cannot change the elements of a tuple once it is assigned whereas in a list, elements
can be changed.

Python Tuple
In this article, you'll learn everything about Python tuples. More specifically, what are tuples,
how to create them, when to use them and various methods you should be familiar with. A
tuple in Python is similar to a list. The difference between the two is that we cannot change the
elements of a tuple once it is assigned whereas we can change the elements of a list.

Creating a Tuple
A tuple is created by placing all the items (elements) inside parentheses (), separated by
commas. The parentheses are optional, however, it is a good practice to use them.A tuple can
have any number of items and they may be of different types (integer, float, list, string, etc.).

# Different types of tuples

# Empty tuple
my_tuple = ()
print(my_tuple)

# Tuple having integers


my_tuple = (1, 2, 3)
print(my_tuple)

# tuple with mixed datatypes


my_tuple = (1, "Hello", 3.4)
print(my_tuple)

# nested tuple
my_tuple = ("mouse", [8, 4, 6], (1, 2, 3))
print(my_tuple)

Output

()
(1, 2, 3)
(1, 'Hello', 3.4)
('mouse', [8, 4, 6], (1, 2, 3))

Gandhinagar Institute of Technology 3150713 PDS


A tuple can also be created without using parentheses. This is known as tuple packing.
my_tuple = 3, 4.6, "dog"
print(my_tuple)

# tuple unpacking is also possible


a, b, c = my_tuple

print(a) #3
print(b) # 4.6
print(c) # dog

Output

(3, 4.6, 'dog')


3
4.6
dog

Creating a tuple with one element is a bit tricky.

Having one element within parentheses is not enough. We will need a trailing comma to
indicate that it is, in fact, a tuple.

my_tuple = ("hello")
print(type(my_tuple)) # <class 'str'>

# Creating a tuple having one element


my_tuple = ("hello",)
print(type(my_tuple)) # <class 'tuple'>

# Parentheses is optional
my_tuple = "hello",
print(type(my_tuple)) # <class 'tuple'>

Output:

<class 'str'>
<class 'tuple'>
<class 'tuple'>

Access Tuple Elements


There are various ways in which we can access the elements of a tuple.
1. Indexing
We can use the index operator [] to access an item in a tuple, where the index starts
from 0. So, a tuple having 6 elements will have indices from 0 to 5. Trying to access an
index outside of the tuple index range(6,7,... in this example) will raise an IndexError.

Gandhinagar Institute of Technology 3150713 PDS


The index must be an integer, so we cannot use float or other types. This will result
in TypeError.
Likewise, nested tuples are accessed using nested indexing, as shown in the example
below.
# Accessing tuple elements using indexing
my_tuple = ('p','e','r','m','i','t')

print(my_tuple[0]) # 'p'
print(my_tuple[5]) # 't'

# IndexError: list index out of range


# print(my_tuple[6])

# Index must be an integer


# TypeError: list indices must be integers, not float
# my_tuple[2.0]

# nested tuple
n_tuple = ("mouse", [8, 4, 6], (1, 2, 3))

# nested index
print(n_tuple[0][3]) # 's'
print(n_tuple[1][1]) #4

Output

p
t
s
4

2. Negative Indexing
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.
# Negative indexing for accessing tuple elements
my_tuple = ('p', 'e', 'r', 'm', 'i', 't')

# Output: 't'
print(my_tuple[-1])

# Output: 'p'
print(my_tuple[-6])

Output

t
p

Gandhinagar Institute of Technology 3150713 PDS


3. Slicing:
We can access a range of items in a tuple by using the slicing operator colon :
# Accessing tuple elements using slicing
my_tuple = ('g','a','n','d','h','i','n','a','g',’a’,’r’)

# elements 2nd to 4th


# Output: ('a', 'n', 'd')
print(my_tuple[1:4])

# elements beginning to 2nd


# Output: ('g', 'a',’n’,d’,’h’,’i’)
print(my_tuple[:-5])

# elements 8th to end


# Output: ('a', 'g', ‘a’,’r’)
print(my_tuple[7:])

# elements beginning to end


# Output: ('g','a','n','d','h','i','n','a','g',’a’,’r’)
print(my_tuple[:])

Output

('a', 'n', 'd')


('g', 'a',’n’,d’,’h’,’i’)
('a', 'g', ‘a’,’r’)
('g','a','n','d','h','i','n','a','g',’a’,’r’)

Slicing can be best visualized by considering the index to be between the elements as shown
below. So if we want to access a range, we need the index that will slice the portion from the
tuple.

Changing a Tuple
Unlike lists, tuples are immutable. This means that elements of a tuple cannot be changed once
they have been assigned. But, if the element is itself a mutable data type like a list, its nested
items can be changed.
We can also assign a tuple to different values (reassignment).
# Changing tuple values
my_tuple = (4, 2, 3, [6, 5])

# TypeError: 'tuple' object does not support item assignment


# my_tuple[1] = 9

# However, item of mutable element can be changed


my_tuple[3][0] = 9 # Output: (4, 2, 3, [9, 5])
print(my_tuple)
Gandhinagar Institute of Technology 3150713 PDS
# Tuples can be reassigned
my_tuple = ('g', 'a', 'n', 'd', 'h', 'i', 'n', 'a', 'g',’a’,’r’)

# Output: ('g', 'a', 'n', 'd', 'h', 'i', 'n', 'a', 'g',’a’,’r’)
print(my_tuple)

Output

(4, 2, 3, [9, 5])


('g', 'a', 'n', 'd', 'h', 'i', 'n', 'a', 'g',’a’,’r’)

We can use + operator to combine two tuples. This is called concatenation.


We can also repeat the elements in a tuple for a given number of times using the * operator.
Both + and * operations result in a new tuple.

# Concatenation
# Output: (1, 2, 3, 4, 5, 6)
print((1, 2, 3) + (4, 5, 6))

# Repeat
# Output: ('Repeat', 'Repeat', 'Repeat')
print(("Repeat",) * 3)

Output

(1, 2, 3, 4, 5, 6)
('Repeat', 'Repeat', 'Repeat')

Deleting a Tuple
As discussed above, we cannot change the elements in a tuple. It means that we cannot delete
or remove items from a tuple.
Deleting a tuple entirely, however, is possible using the keyword del.

# Deleting tuples
my_tuple = ('g', 'a', 'n', 'd', 'h', 'i', 'n', 'a', 'g', ’a’, ’r’)

# can't delete items


# TypeError: 'tuple' object doesn't support item deletion
# del my_tuple[3]

# Can delete an entire tuple


del my_tuple

# NameError: name 'my_tuple' is not defined


print(my_tuple)

Gandhinagar Institute of Technology 3150713 PDS


Output

Traceback (most recent call last):


File "<string>", line 12, in <module>
NameError: name 'my_tuple' is not defined

Tuple Methods

Methods that add items or remove items are not available with tuple. Only the following two
methods are available.

Some examples of Python tuple methods:


my_tuple = ('a', 'p', 'p', 'l', 'e',)

print(my_tuple.count('p')) # Output: 2
print(my_tuple.index('l')) # Output: 3

Output

2
3

Other Tuple Operations


1. Tuple Membership Test
We can test if an item exists in a tuple or not, using the keyword in.
# Membership test in tuple
my_tuple = ('a', 'p', 'p', 'l', 'e',)

# In operation
print('a' in my_tuple)
print('b' in my_tuple)

# Not in operation
print('g' not in my_tuple)

Output

True
False
True

2. Iterating Through a Tuple


We can use a for loop to iterate through each item in a tuple.
# Using a for loop to iterate through a tuple
for name in ('John', 'Kate'):
print("Hello", name)
Gandhinagar Institute of Technology 3150713 PDS
Output

Hello John
Hello Kate

Advantages of Tuple over List


Since tuples are quite similar to lists, both of them are used in similar situations. However,
there are certain advantages of implementing a tuple over a list. Below listed are some of the
main advantages:
• We generally use tuples for heterogeneous (different) data types and lists for
homogeneous (similar) data types.
• Since tuples are immutable, iterating through a tuple is faster than with list. So there is
a slight performance boost.
• Tuples that contain immutable elements can be used as a key for a dictionary. With
lists, this is not possible.
• If you have data that doesn't change, implementing it as tuple will guarantee that it
remains write-protected.

Exercises:
1. Reverse the following tuple
aTuple = (10, 20, 30, 40, 50)
2. Access value 20 from the following tuple
aTuple = ("Orange", [10, 20, 30], (5, 15, 25))
3. Unpack the following tuple into 4 variables.
aTuple = (10, 20, 30, 40)
4. Swap the following two tuples
tuple1 = (11, 22)
tuple2 = (99, 88)
5. Modify the first item (22) of a list inside a following tuple to 222
tuple1 = (11, [22, 33], 44, 55)

Review Questions:
1. What is a tuple?
2. Differentiate between a tuple and a list?

Gandhinagar Institute of Technology 3150713 PDS


DATA STRUCTURE-1 IN PYTHON
Practical No: ________ Date: _________

Aim: To Implement Stack, Queue using list.

Theory:

Stack Data Structure


In this tutorial, you will learn about the stack data structure and its implementation in Python.

A stack is a linear data structure that follows the principle of Last In First Out (LIFO). This
means the last element inserted inside the stack is removed first. You can think of the stack
data structure as the pile of plates on top of another.
Here, you can:
Put a new plate on top
Remove the top plate
And, if you want the plate at the bottom, you must first remove all the plates on top. This is
exactly how the stack data structure works.

LIFO Principle of Stack


In programming terms, putting an item on top of the stack is called push and removing an item
is called pop.

Figure 1Stack Push and Pop Operations

In the above image, although item 2 was kept last, it was removed first. This is exactly how
the LIFO (Last In First Out) Principle works.We can implement a stack in any programming
language like C, C++, Java, Python or C#, but the specification is pretty much the same.

Basic Operations of Stack


There are some basic operations that allow us to perform different actions on a stack.
Push: Add an element to the top of a stack
Pop: Remove an element from the top of a stack
Gandhinagar Institute of Technology 3150713 PDS
IsEmpty: Check if the stack is empty
IsFull: Check if the stack is full
Peek: Get the value of the top element without removing it

Working of Stack Data Structure


The operations work as follows:
1. A pointer called TOP is used to keep track of the top element in the stack.
2. When initializing the stack, we set its value to -1 so that we can check if the stack is
empty by comparing TOP == -1.
3. On pushing an element, we increase the value of TOP and place the new element in the
position pointed to by TOP.
4. On popping an element, we return the element pointed to by TOP and reduce its value.
5. Before pushing, we check if the stack is already full
6. Before popping, we check if the stack is already empty.

Figure 2Working of Stack Data Structure

Stack Implementations in Python


The most common stack implementation is using arrays, but it can also be implemented using
lists.
# Stack implementation in python
# Creating a stack
def create_stack():
stack = []
return stack

# Creating an empty stack


def check_empty(stack):
return len(stack) == 0

# Adding items into the stack


def push(stack, item):
stack.append(item)
print("pushed item: " + item)

# Removing an element from the stack


def pop(stack):
Gandhinagar Institute of Technology 3150713 PDS
if (check_empty(stack)):
return "stack is empty"

return stack.pop()

stack = create_stack()
push(stack, str(1))
push(stack, str(2))
push(stack, str(3))
push(stack, str(4))
print("popped item: " + pop(stack))
print("stack after popping an element: " + str(stack))

Output:

pushed item: 1
pushed item: 2
pushed item: 3
pushed item: 4
popped item: 4
stack after popping an element: ['1', '2', '3']

Stack Time Complexity


For the array-based implementation of a stack, the push and pop operations take constant time,
i.e. O(1).

Applications of Stack Data Structure


Although stack is a simple data structure to implement, it is very powerful. The most common
uses of a stack are:

To reverse a word - Put all the letters in a stack and pop them out. Because of the LIFO order
of stack, you will get the letters in reverse order.

In compilers - Compilers use the stack to calculate the value of expressions like 2 + 4 / 5 * (7
- 9) by converting the expression to prefix or postfix form.

In browsers - The back button in a browser saves all the URLs you have visited previously in
a stack. Each time you visit a new page, it is added on top of the stack. When you press the
back button, the current URL is removed from the stack, and the previous URL is accessed.

Queue Data Structure


In this tutorial, you will learn what a queue is. Also, you will find implementation of queue in
Python. A queue is a useful data structure in programming. It is similar to the ticket queue
outside a cinema hall, where the first person entering the queue is the first person who gets the
ticket.
Queue follows the First In First Out (FIFO) rule - the item that goes in first is the item that
comes out first.
Gandhinagar Institute of Technology 3150713 PDS
Figure 3FIFO Representation of Queue

In the above image, since 1 was kept in the queue before 2, it is the first to be removed from
the queue as well. It follows the FIFO rule. In programming terms, putting items in the queue
is called enqueue, and removing items from the queue is called dequeue. We can implement
the queue in any programming language like C, C++, Java, Python or C#, but the specification
is pretty much the same.

Basic Operations of Queue


A queue is an object (an abstract data structure - ADT) that allows the following operations:
Enqueue: Add an element to the end of the queue
Dequeue: Remove an element from the front of the queue
IsEmpty: Check if the queue is empty
IsFull: Check if the queue is full
Peek: Get the value of the front of the queue without removing it

Working of Queue
Queue operations work as follows:
• two pointers FRONT and REAR
• FRONT track the first element of the queue
• REAR track the last element of the queue
• initially, set value of FRONT and REAR to -1
Enqueue Operation
• check if the queue is full
• for the first element, set the value of FRONT to 0
• increase the REAR index by 1
• add the new element in the position pointed to by REAR
Dequeue Operation
• check if the queue is empty
• return the value pointed by FRONT
• increase the FRONT index by 1
• for the last element, reset the values of FRONT and REAR to -1

Gandhinagar Institute of Technology 3150713 PDS


Figure 4Enqueue and Dequeue Operations

Gandhinagar Institute of Technology 3150713 PDS


Queue Implementations in Python
We usually use arrays to implement queues in Java and C/++. In the case of Python, we use
lists.
# Queue implementation in Python

class Queue:

def __init__(self):
self.queue = []

# Add an element
def enqueue(self, item):
self.queue.append(item)

# Remove an element
def dequeue(self):
if len(self.queue) < 1:
return None
return self.queue.pop(0)

# Display the queue


def display(self):
print(self.queue)

def size(self):
return len(self.queue)

q = Queue()
q.enqueue(1)
q.enqueue(2)
q.enqueue(3)

Output:

[1, 2, 3, 4, 5]
After removing an element
[2, 3, 4, 5]

Limitations of Queue
As you can see in the image below, after a bit of enqueuing and dequeuing, the size of the
queue has been reduced.

Figure 5Limitation of a queue

Gandhinagar Institute of Technology 3150713 PDS


And we can only add indexes 0 and 1 only when the queue is reset (when all the elements have
been dequeued). After REAR reaches the last index, if we can store extra elements in the empty
spaces (0 and 1), we can make use of the empty spaces. This is implemented by a modified
queue called the circular queue.

Complexity Analysis
The complexity of enqueue and dequeue operations in a queue using an array is O(1). If you
use pop(N) in python code, then the complexity might be O(n) depending on the position of
the item to be popped.

Applications of Queue
• CPU scheduling, Disk Scheduling
• When data is transferred asynchronously between two processes. The queue is used for
synchronization. For example: IO Buffers, pipes, file IO, etc
• Handling of interrupts in real-time systems.
• Call Center phone systems use Queues to hold people calling them in order.

Exercises:
1. Circular Queue implementation in Python.
2. Priority Queue implementation in Python.
3. Deque implementation in python.
4. Write a Python program to insert items into a list in sorted order.
Expected Output:
Original List:
[25, 45, 36, 47, 69, 48, 68, 78, 14, 36]
Sorted List:
[14, 25, 36, 36, 45, 47, 48, 68, 69, 78]
5. Write a Python program to find whether a queue is empty or not.

Review Questions:
1. What is Stack and how implementation of Stack in c is different from python?
2. Difference between queue and stack?

Gandhinagar Institute of Technology 3150713 PDS

You might also like