0% found this document useful (0 votes)
24 views

Final Lab Manual

The document provides instructions for installing and using software for a programming lab manual. It outlines installing Python, running Python in a terminal, installing VS Code, and using Jupyter notebooks. It then describes several labs covering Python data types, lists, loops, and tuples to demonstrate Python concepts.

Uploaded by

star light
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views

Final Lab Manual

The document provides instructions for installing and using software for a programming lab manual. It outlines installing Python, running Python in a terminal, installing VS Code, and using Jupyter notebooks. It then describes several labs covering Python data types, lists, loops, and tuples to demonstrate Python concepts.

Uploaded by

star light
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 30

LAB

MANUAL
Course: Programming Language for Business
Analytics

Department of Management
Sciences

Mgt173 Programming Language for Business Analytics


–Lab Manual
COMSATS University, Islamabad
Table of Contents
Preamble.................................................................................................................................................................................................... 3
I. Tools/Software Requirements................................................................................................................................................ 3
A. Installing Python...........................................................................................................................................3
B. Running Python in a Terminal Session..........................................................................................................4
C. Installing VS Code.........................................................................................................................................4
Simplifying output................................................................................................................................................4
D. Using a Jupiter Notebook.............................................................................................................................7
I. LAB 01: Types of Data................................................................................................................................................................. 8
A. Purpose........................................................................................................................................................8
B. Outcomes.....................................................................................................................................................8
C. Instructor Note.............................................................................................................................................8
D. Stage J (Journey)...........................................................................................................................................8
Python Data Types................................................................................................................................................8
Python String Data type.......................................................................................................................................9
E. Apply..........................................................................................................................................................10
II. LAB 02: List................................................................................................................................................................................... 14
A. Purpose......................................................................................................................................................14
B. Outcomes...................................................................................................................................................14
C. Instructor Note...........................................................................................................................................14
D. Stage J (Journey).........................................................................................................................................14
E. Apply..........................................................................................................................................................15
F. Assignment 1..............................................................................................................................................15
III. LAB 03: List, For Loops............................................................................................................................................................ 17
A. Purpose......................................................................................................................................................17
B. Outcomes...................................................................................................................................................17
C. Instructor Note...........................................................................................................................................17
D. Stage J (Journey).........................................................................................................................................17
E. Apply: Python for loop to iterate through the letters in a word.................................................................17
F. Apply: Python for loop using the range() function......................................................................................17

Mgt173 Programming Language for Business Analytics


–Lab Manual
G. Apply: Python for loop to iterate through a list..........................................................................................17
H. Apply: Python for loop using the zip() function for parallel iteration.........................................................18
I. Apply: Using else statement inside a for loop in Python............................................................................18
J. Apply: Nested for loops in Python (one loop inside another loop).............................................................18
K. Apply: Using break statement inside a for loop in Python..........................................................................19
L. Apply: Using continue statement inside a for loop in Python.....................................................................19
M. Apply: Python for loop to count the number of elements in a list..............................................................20
N. Apply: Python for loop to copy elements from one list to another............................................................20
O. Apply: Python for loop to print the multiples of 5 using range() function..................................................21
P. Apply: Python for loop to print the numbers in reverse order using range() function...............................21
Q. Quiz 1..........................................................................................................................................................21
IV. LAB 04: Tuples........................................................................................................................................................................ 23
A. Purpose......................................................................................................................................................23
B. Outcomes...................................................................................................................................................23
C. Instructor Note...........................................................................................................................................23
D. Stage J (Journey).........................................................................................................................................23
E. Apply..........................................................................................................................................................28

Mgt173 Programming Language for Business Analytics


–Lab Manual
MGT173 Programming Language for Business 4
Anlytics
Preamble

In this course, we are going to learn and practice concepts related to python. In this lab manual, to demonstrate
various python concepts, we are going to use Jupiter Notebook within VS Code

I. Tools/Software Requirements
Following are the software that we will need for this lab manual:
 Python
 VS Code

A. Installing Python
First, check whether Python is installed on your system. Open a command window by entering command into the
Start menu and clicking the Command Prompt app. In the terminal window, enter python in lowercase. If you get
a Python prompt (>>>) in response, Python is installed on your system. If you see an error message telling you
that python is not a recognized command, or if the Microsoft store opens, Python isn’t installed. Close the
Microsoft store if it opens; it’s better to download an official installer than to use Microsoft’s version.
If Python is not installed on your system, or if you see a version earlier than Python 3.9, you need to download a
Python installer for Windows. Go to https://python.org and hover over the Downloads link. You should see a
button for downloading the latest version of Python. Click the button, which should automatically start
downloading the correct installer for your system. After you’ve downloaded the file, run the installer. Make sure
you select the option Add Python to PATH, which will make it easier to configure your system correctly. Figure
1-1 shows this option selected.

MGT173 Programming Language for Business 5


Anlytics
Figure 1-1: Make sure you select the checkbox labeled Add Python to PATH.

B. Running Python in a Terminal Session


Open a new command window and enter python in lowercase. You should see a Python prompt (>>>), which
means Windows has found the version of Python you just installed.
C:\> python
Python 3.x.x (main, Jun . . . , 13:29:14) [MSC v.1932 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>

C. Installing VS Code
You can download an installer for VS Code at https://code.visu alstudio.com. Click the Download for Windows
button and run the installer.
Configuring VS Code
VS Code is a great text editor, with some features that you'd typically see in an IDE. There are some helpful
recommendations for configuring VS Code and using it efficiently in Appendix B of the book. This section shows
some of those same configuration steps, with more screenshots.

Simplifying output

MGT173 Programming Language for Business 6


Anlytics
By default, VS Code displays output in an integrated terminal. This is a terminal window that's embedded within
the VS Code application. It's nice because you don't have to have a separate terminal window open to see your
output, but it can be confusing because it displays a lot more information than you might want to see when you're
running your first programs.
For example, here's what VS Code looks like when you run hello_world.py:

The output we're really interested in is the single line Hello Python world! The rest of the output shows where the
file is being saved, and the path to the Python interpreter that's being used to run the program. At this point you
probably just want to see the output of your program.
To see just the output, do the following:
 Close all open tabs in VS Code, and quit VS Code.
 Launch VS Code again and open the folder that contains the Python files you're working on.
 Click the Run/ Debug icon:

 Click Create a launch.json File, and select the Python File option:

In the configurations section, change the console setting from integratedTerminal to internalConsole:


launch.json
{
...

MGT173 Programming Language for Business 7


Anlytics
"configurations": [
{
"name": "Python: Current File",
"type": "python",
"request": "launch",
"program": "${file}",
"console": "internalConsole"
}
]
}
Now, run your .py file again and click on the Debug Console tab in the bottom pane. You should see just your
program's output:

Running programs that use input()


If you made the above change to display output in the Debug Console instead of the integrated terminal window,
you won't be able to run programs that use the input() function. The Debug Console is read-only, which means it
doesn't accept input. When you're running programs using the input() function, which is introduced in Chapter 7,
you'll need to switch back to using the integrated terminal.
To do this, open the launch.json file that you created earlier, and change internalConsole back
to integratedTerminal:
launch.json
{
...
"configurations": [
{

MGT173 Programming Language for Business 8


Anlytics
"name": "Python: Current File",
"type": "python",
"request": "launch",
"program": "${file}",
"console": "integratedTerminal"
}
]
}

Switching between the editor and the terminal


When you're running programs that use input(), you'll need to switch between the editor pane where you're typing
code, and the terminal where you'll enter input. You can use a mouse or a trackpad, but there's a keyboard
shortcut that's really helpful.
When you're finished entering code in the editor pane, press Ctrl-F5 to run your program. You'll see a prompt in
the terminal pane where you can enter the input for the program. Press Ctrl-` (Control-backtick) to switch from
the editor pane to the terminal pane. When you're finished entering input, press  Ctrl-` again to move the cursor
back to the editor window.

D. Using a Jupiter Notebook


Jupiter notebook is installed in VS code as an extension. Open a new file and select the Jupiter notebook. In the
file type, go at the bottom and choose no extension while at the end of the file name write .ipynb
You have just created your first Jupiter notebook.
To run a cell press Ctrl + enter and to run a cell and go to the next cell press Shift+enter

MGT173 Programming Language for Business 9


Anlytics
I. LAB 01: Types of Data

A. Purpose
The purpose of this lab is to introduce the different types of data that are used in python programming.

B. Outcomes
After completing this lesson, students should be able to do the following:
 Identify different data types of data
 Run different methods on data types

C. Instructor Note
As a pre-lab activity, please attend the theory classes on data types.

D. Stage J (Journey)
Data Types

Python uses different data types;


Python Data Types

Data Types Classes Description

int, float,
Numeric holds numeric values
complex

String str holds sequence of characters

Sequence list, tuple, range holds collection of items

Mapping dict holds data in key-value pair form

Boolean bool holds either True or False

Set set, frozeenset hold collection of unique items

MGT173 Programming Language for Business 10


Anlytics
Classes provide a means of bundling data
An object is called an instance of a class. For example, suppose Bike is a class then we can create objects like
bike1 , bike2 , etc from the class. Here's the syntax to create an object. Here, bike1 is the object of the class.
Method is a function that “belongs to” an object. (In Python, the term method is not unique to class instances:
other object types can have methods as well. For example, list objects have methods called append, insert,
remove, sort, and so on.
A function is a block of code which only runs when it is called. You can pass data, known as parameters, into a
function. A function can return data as a result.
Python Numeric Data Type
In Python, numeric data type is used to hold numeric values.
Integers, floating-point numbers and complex numbers fall under Python numbers category. They are defined
as int, float and complex classes in Python.
 int - holds signed integers of non-limited length.
 float - holds floating decimal points and it's accurate up to 15 decimal places.
 complex - holds complex numbers. The complex number is the combination of a real number and
imaginary number. An example of a complex number is 4+3i.
We can use the type() function to know which class a variable or a value belongs to.
Python String Data type
Python string data type is a sequence of characters. For example, "hello" is a string containing a sequence of
characters 'h', 'e', 'l', 'l', and 'o'. We use single quotes or double quotes to represent a string in Python. There are
various string methods present in Python. Here are some of those methods:

Methods Description

upper() converts the string to uppercase

lower() converts the string to lowercase

partition() returns a tuple

replace() replaces substring inside

MGT173 Programming Language for Business 11


Anlytics
returns the index of first occurrence of
find()
substring

rstrip() removes trailing characters

split() splits string from left

startswith() checks if string starts with the specified string

isnumeric(
checks numeric characters
)

index() returns index of substring

E. Apply
Lab Activity 1: identify the type of numeric data
This lab activity demonstrates the use of type method to identify the data type which is numeric.
Solution:
num1 = 5
print(num1, 'is of type', type(num1))

num2 = 2.0
print(num2, 'is of type', type(num2))

num3 = 1+2j
print(num3, 'is of type', type(num3))
Output

5 is of type <class 'int'>


2.0 is of type <class 'float'>
(1+2j) is of type <class 'complex'>

MGT173 Programming Language for Business 12


Anlytics
In the above example, we have created three variables amed num1, num2 and num3 with values 5, 5.0,
and 1+2j respectively. We have also used the type() function to know which class a certain variable belongs to.
Since, 5 is an integer value, type() returns int as the class of num1 i.e <class 'int'> 2.0 is a floating
value, type() returns float as the class of num2 i.e <class 'float'> 1 + 2j is a complex
number, type() returns complex as the class of num3 i.e <class 'complex'>
Lab Activity 2: Use different methods on strings
This lab activity demonstrates the codes which will enable students to understand strings
name = 'Python'
print(name)

message = 'Python for beginners'


print(message)

Python
Python for beginners

In the above example, we have created string-type variables: name and message with values 'Python' and 'Python
for beginners' respectively.

# create a string using double quotes


string1 = "Python programming"

# create a string using single quotes


string1 = 'Python programming'

Here, we have created a string variable named string1. The variable is initialized with the string Python
Programming.# create string type variables

name = "Python"
print(name)

message = "I love Python."


print(message)

MGT173 Programming Language for Business 13


Anlytics
Python
I love Python.

In the above example, we have created string-type variables: name and message with values "Python" and "I love
Python" respectively. Here, we have used double quotes to represent strings but we can use single quotes too.
Access String Characters in Python
We can access the characters in a string in three ways.
Indexing: One way is to treat strings as a list and use index values.
Negative Indexing: Similar to a list, Python allows negative indexing for its strings. For example,
greet = 'hello'

# access 1st index element


print(greet[1]) # "e"

greet = 'hello'

# access 4th last element


print(greet[-4]) # "e"

Slicing: Access a range of characters in a string by using the slicing operator colon :. For example,
greet = 'Hello'

# access character from 1st index to 3rd index


print(greet[1:4]) # "ell"

Note: If we try to access an index out of the range or use numbers other than an integer, we will get errors.
Python Strings are immutable
In Python, strings are made immutable so that programmers cannot alter the contents of the object (even by
mistake). 
message = 'Hola Amigos'
message[0] = 'H'
print(message)

MGT173 Programming Language for Business 14


Anlytics
TypeError: 'str' object does not support item assignment

However, we can assign the variable name to a new string. For example,
message = 'Hola Amigos'

# assign new string to message variable


message = 'Hello Friends'

prints(message); # prints "Hello Friends"

Python Multiline String


We can also create a multiline string in Python. For this, we use triple double quotes """ or triple single quotes '''.
For example,
# multiline string
message = """
Never gonna give you up
Never gonna let you down
"""

print(message)
Run Code

Never gonna give you up


Never gonna let you down

In the above example, anything inside the enclosing triple-quotes is one multiline string.

MGT173 Programming Language for Business 15


Anlytics
II. LAB 02: List

A. Purpose
The purpose of this lab is to practice the concepts of list hat are used in python programming.

B. Outcomes
After completing this lesson, students should be able to do the following:
 Identify and know the different list methods

C. Instructor Note
As a pre-lab activity, please attend the theory classes on data types.

D. Stage J (Journey)
The list functions are of the following types
Commonly Used Python List Built-in Functions

len() returns list length

sort() sorts the list

min() returns the minimum value from list

max() returns the maximum value from list

list() converts a sequential data type to list

append() adds an element at the end of the list

clear() removes all elements from the list

copy() returns the copied list

reverse() reverses the order of the elements of the list

sum() returns the sum of the elements of the list

range() returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and stops before a specified number

pop() removes the element at the specified position

MGT173 Programming Language for Business 16


Anlytics
remove() removes the item with the specified value

index() returns the index of the first element with the specified value

insert() Adds an element at the specified position

E. Apply
1. Create a list of five of your favorite foods.
2. From your list of favorite foods, select the second item.
3. "my name is john".upper() returns the string “MY NAME IS JOHN”. Given that fact, create an
uppercase list of your favorite foods. Hint: You would need to convert your list in to string first.
4. Add another food item in your favorite food list.
5. Delete the first element of your list.
6. Using the .pop() command, pop the food that you don’t like anymore and place it in a variable
called not_liked
7. Sort your list in reverse order.

For the following list

letters = ['A', 'B', 'C', 'D', 'E', 'F', 'G']

8. Use a function to get the length of the letters list. Display it.
9. Get the last item in the list, using a positive index.
10. Get the last item in the list, using a negative index.
11. How could you return a list that looks like the list below:
['G', 'F', 'E', 'D', 'C', 'B', 'A']

F. Assignment 1
1.Guest List: If you could invite anyone, living or deceased, to dinner, who would you invite?
Make a list that includes at least three people you’d like to invite to dinner.
Then use your list to print a message to each person, inviting them to dinner.
2.Changing Guest List: You just heard that one of your guests can’t make the dinner, so you need to send out a
new set of invitations. You’ll have to think of someone else to invite.
Start with your program from Exercise 1.
Add a print() call at the end of your program, stating the name of the guest who can’t make it.
Modify your list, replacing the name of the guest who can’t make it with the name of the new person you are
inviting.
Print a second set of invitation messages, one for each person who is still in your list.
3.More Guests: You just found a bigger dinner table, so now more space is available.
Think of three more guests to invite to dinner. Start with your program from Exercise 1 or 2

MGT173 Programming Language for Business 17


Anlytics
Add a print() call to the end of your program, informing people that you found a bigger table.
Use insert() to add one new guest to the beginning of your list.
Use insert() to add one new guest to the middle of your list.
Use append() to add one new guest to the end of your list.
Print a new set of invitation messages, one for each person in your list.
4.Shrinking Guest List: You just found out that your new dinner table won’t arrive in time for the dinner, and now
you have space for only two guests.
Start with your program from Exercise 3.
Add a new line that prints a message saying that you can invite only two people for dinner.
Use pop() to remove guests from your list one at a time until only two names remain in your list.
Each time you pop a name from your list, print a message to that person letting them know you’re sorry you can’t
invite them to dinner.
Print a message to each of the two people still on your list, letting them know they’re still invited.
Use del to remove the last two names from your list, so you have an empty list.
Print your list to make sure you actually have an empty list at the end of your program.

MGT173 Programming Language for Business 18


Anlytics
III. LAB 03: List, For Loops

A. Purpose
The purpose of this lab is to introduce the for loops that are used in python programming.

B. Outcomes
After completing this lesson, students should be able to do the following:
 Understand application for Python Loops

C. Instructor Note
As a pre-lab activity, please attend the theory classes on for loops.

D. Stage J (Journey)

In Python programming, we use for loops to repeat some code a certain number of times. It allows us to execute a
statement or a group of statements multiple times by reducing the burden of writing several lines of code.

E. Apply: Python for loop to iterate through the letters in a word


for i in "pythonista":

print(i)

F. Apply: Python for loop using the range() function


for j in range(5):

print(j)

G. Apply: Python for loop to iterate through a list


AnimalList = ['Cat','Dog','Tiger','Cow']

for x in AnimalList:

print(x)

MGT173 Programming Language for Business 19


Anlytics
H. Apply: Python for loop using the zip() function for parallel
iteration
a1 = ['Python','Java','CSharp']

b2 = [1,2,3]

for i,j in zip(a1,b2):

print(i,j)

I. Apply: Using else statement inside a for loop in Python


flowers = ['Jasmine','Lotus','Rose','Sunflower']

for f in flowers:

print(f)

else:

print('Done')

Qs. What is an else statement in python: Google and write your answer here.

J. Apply: Nested for loops in Python (one loop inside another


loop)
list1 = [5,10,15,20]

list2 = ['Tomatoes','Potatoes','Carrots','Cucumbers']

MGT173 Programming Language for Business 20


Anlytics
for x in list1:

for y in list2:

print(x,y)

 A nested loop has one loop inside of another. These are typically used for working with two dimensions such as
printing stars in rows and columns as shown below. When a loop is nested inside another loop, the inner loop runs
many times inside the outer loop.

K. Apply: Using break statement inside a for loop in Python


vehicles = ['Car','Cycle','Bus','Tempo']

for v in vehicles:

if v == "Bus":

break

print(v)

Whats a break statement:

L. Apply: Using continue statement inside a for loop in Python


vehicles = ['Car','Cycle','Bus','Tempo']

for v in vehicles:

if v == "Bus":

continue

print(v)

Whats a count statement?

MGT173 Programming Language for Business 21


Anlytics
M. Apply: Python for loop to count the number of elements in a
list
numbers = [12,3,56,67,89,90]

count = 0

for n in numbers:

count += 1

print(count)

# you can use len(numbers) also to get the count

N. Apply: Python for loop to copy elements from one list to


another
list1 = ['Mango','Banana','Orange']

list2 = []

for i in list1:

list2.append(i)

print(list2)

MGT173 Programming Language for Business 22


Anlytics
O. Apply: Python for loop to print the multiples of 5 using
range() function
# printing multiples of 5 till 20

for i in range(5,20,5):

print(i)

P. Apply: Python for loop to print the numbers in reverse order


using range() function
for i in range(10,0,-1):

print(i)

Q. Quiz 1

1. Counting to Twenty: Use a for loop to print the numbers from 1 to 20, inclusive.
2. Summing a Million: Make a list of the numbers from one to one million, and then use min() and max() to make
sure your list actually starts at one and ends at one million. Also, use the sum() function to see how quickly
Python can add a million numbers.
3. Odd Numbers: Use the third argument of the range() function to make a list of the odd numbers from 1 to 20.
Use a for loop to print each number.
4. Threes: Make a list of the multiples of 3, from 3 to 30. Use a for loop to print the numbers in your list.
5. Cubes: A number raised to the third power is called a cube. For example, the cube of 2 is written as 2**3 in
Python. Make a list of the first 10 cubes (that is, the cube of each integer from 1 through 10), and use a for loop
to print out the value of each cube.
6. Cube Comprehension: Use a list comprehension to generate a list of the first 10 cubes.

MGT173 Programming Language for Business 23


Anlytics
7. Pizzas: Think of at least three kinds of your favorite pizza. Store these pizza names in a list, and then use a for
loop to print the name of each pizza.
Modify your for loop to print a sentence using the name of the pizza, instead of printing just the name of the
pizza. For each pizza, you should have one line of output containing a simple statement like I like pepperoni
pizza.
Add a line at the end of your program, outside the for loop, that states how much you like pizza. The output
should consist of three or more lines about the kinds of pizza you like and then an additional sentence, such as I
really love pizza!

MGT173 Programming Language for Business 24


Anlytics
IV. LAB 04: Tuples

A. Purpose
The purpose of this lab is to introduce the concept of tuples that are used in python programming.

B. Outcomes
After completing this lesson, students should be able to do the following:
 Understand tuples and their usage

C. Instructor Note
As a pre-lab activity, please attend the theory classes on tuples

D. Stage J (Journey)
Tuple is one of 4 built-in data types in Python used to store collections of data, the other 3 are List, Set, and
Dictionary, all with different qualities and usage.

A tuple is a collection of objects which ordered and immutable. Tuples are sequences, just like lists. The
differences between tuples and lists are, the tuples cannot be changed unlike lists and tuples use parentheses,
whereas lists use square brackets.
Creating a tuple is as simple as putting different comma-separated values. Optionally you can put these comma-
separated values between parentheses also. For example −
tup1 = ('physics', 'chemistry', 1997, 2000);
tup2 = (1, 2, 3, 4, 5 );
tup3 = "a", "b", "c", "d";
The empty tuple is written as two parentheses containing nothing −
tup1 = ();
To write a tuple containing a single value you have to include a comma, even though there is only one value −
tup1 = (50,);
Like string indices, tuple indices start at 0, and they can be sliced, concatenated, and so on.

# Different types of tuples

# Empty tuple
my_tuple = ()
print(my_tuple)

# Tuple having integers


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

MGT173 Programming Language for Business 25


Anlytics
# 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)

Create a Python Tuple With one Element


In Python, 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 a tuple

var1 = ("Hello") # string


var2 = ("Hello",) # tuple

We can use the type() function to know which class a variable or a value belongs to.
var1 = ("hello")
print(type(var1)) # <class 'str'>

# Creating a tuple having one element


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

# Parentheses is optional
var3 = "hello",
print(type(var3)) # <class 'tuple'>
Here,
("hello") is a string so type() returns str as class of var1 i.e. <class 'str'>
("hello",) and "hello", both are tuples so type() returns tuple as class of var1 i.e. <class 'tuple'>
Accessing Values in Tuples
To access values in tuple, use the square brackets for slicing along with the index or indices to obtain value
available at that index.

# accessing tuple elements using indexing


letters = ("p", "r", "o", "g", "r", "a", "m", "i", "z")

print(letters[0]) # prints "p"


print(letters[5]) # prints "a"

# accessing tuple elements using negative indexing

MGT173 Programming Language for Business 26


Anlytics
letters = ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')

print(letters[-1]) # prints 'z'


print(letters[-3]) # prints 'm'

Slicing
We can access a range of items in a tuple by using the slicing operator colon

# accessing tuple elements using slicing


my_tuple = ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')

# elements 2nd to 4th index


print(my_tuple[1:4]) # prints ('r', 'o', 'g')

# elements beginning to 2nd


print(my_tuple[:-7]) # prints ('p', 'r')

# elements 8th to end


print(my_tuple[7:]) # prints ('i', 'z')

# elements beginning to end


print(my_tuple[:]) # Prints ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')

Python Tuple Methods


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

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

print(my_tuple.count('p')) # prints 2
print(my_tuple.index('l')) # prints 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 = ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')

# elements 2nd to 4th index


print(my_tuple[1:4]) # prints ('r', 'o', 'g')

MGT173 Programming Language for Business 27


Anlytics
# elements beginning to 2nd
print(my_tuple[:-7]) # prints ('p', 'r')

# elements 8th to end


print(my_tuple[7:]) # prints ('i', 'z')

# elements beginning to end


print(my_tuple[:]) # Prints ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')

Iterating through a Tuple in Python


We can use the for loop to iterate over the elements of a tuple. For example,

languages = ('Python', 'Swift', 'C++')

# iterating through the tuple


for language in languages:
print(language)

Check if an Item Exists in the Python Tuple

We use the in keyword to check if an item exists in the tuple or not. For example,

languages = ('Python', 'Swift', 'C++')

print('C' in languages) # False


print('Python' in languages) # True

Concatenation of Python Tuples

To concatenate the Python tuple we will use plus operators(+).

# Code for concatenating 2 tuples


 
tuple1 = (0, 1, 2, 3)
tuple2 = ('python', 'geek')
 
# Concatenating above two
print(tuple1 + tuple2)

Nesting of Python Tuples

MGT173 Programming Language for Business 28


Anlytics
# Code for creating nested tuples
 
tuple1 = (0, 1, 2, 3)
tuple2 = ('python', 'geek')
tuple3 = (tuple1, tuple2)
print(tuple3)

Repetition Python Tuples

# Code to create a tuple with repetition


 
tuple3 = ('python',)*3
print(tuple3)

Immutable Python Tuples

# code to test that tuples are immutable


 
tuple1 = (0, 1, 2, 3)
tuple1[0] = 4
print(tuple1)

Finding Length of a Tuple

# Code for printing the length of a tuple


 
tuple2 = ('python', 'geek')
print(len(tuple2))

Converting list to a Tuple

list1 = [0, 1, 2]
print(tuple(list1))

Advantages of Tuple over List in Python

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:

1. We generally use tuples for heterogeneous (different) data types and lists for homogeneous (similar) data types.

MGT173 Programming Language for Business 29


Anlytics
2. Since tuples are immutable, iterating through a tuple is faster than with a list. So there is a slight performance
boost.

3. If you have data that doesn't change, implementing it as tuple will guarantee that it remains write-protected.

E. Apply
1. Write a Python program to create a tuple

2. Write a Python program to create a tuple with different data types

3. Write a Python program to get the 4th element from the last element of a tuple

4. Write a Python program to check whether an element exists within a tuple

5. Write a Python program to convert a list to a tuple

6. Write a Python program to convert a list to a tuple

7. Write a Python program to reverse a tuple

8. Write a program to copy elements 44 and 55 from the following tuple into a new tuple.

tuple1 = (11, 22, 33, 44, 55, 66)

expected output

tuple2: (44, 55)

MGT173 Programming Language for Business 30


Anlytics

You might also like