CpEProg2 Lab6
CpEProg2 Lab6
Programming Logic
and Design 2 0
Name : ____________________ 6
Date: __________________
Rating: _________________
Experiment #6:
Python Tuples
I. Learning Outcomes:
At the end of this laboratory experiment, the students should be able to:
a) Demonstrate the different ways of creating, accessing, and manipulating tuples in
python
II. Materials:
Laptop/Desktop
Internet Connection
Code editor: PyCharm
III. Overview:
Tuples
Characteristics:
Tuple is exactly same as List except that it is immutable. i.e., once we creates Tuple
object, we cannot perform any changes in that object. Hence, Tuple is Read Only
Version of List.
If the data is fixed and never changes then go for Tuple.
Insertion Order is preserved.
Duplicates are allowed.
Heterogeneous objects are allowed.
We can preserve insertion order and we can differentiate duplicate objects by using
index. Hence, index will play a very important role in Tuple also.
We can represent Tuple elements within Parenthesis and with comma separator.
IV. Procedures/Problems:
A. Creating a Tuple
a. Create a new tuple and assign it to a variable. Type the following:
t=10,20,30,40
print(type(t))
t = ()
t=(10,20,30,40) print(type(t))
print(type(t))
b. Answer the question below. Write beside each item if that is a valid tuple or not.
c. Access individual elements of the tuple by their index. Remember that the first
element of a list has an index of 0. Type the following:
C. Tuple Operations
d. Since tuples are immutable, you cannot modify their elements. However, you can
create a new tuple by concatenating two or more tuples:
# Concatenating tuples
tuple1 = ('apple', 'banana', 'cherry')
tuple2 = ('orange', 'mango', 'grape')
new_tuple = tuple1 + tuple2
print(new_tuple)
e. Python tuples have two built-in methods: count() and index(). The count() method
returns the number of times a specified element appears in a tuple, while the index()
method returns the index of the first occurrence of a specified element in a tuple:.
Type the following:
f. Tuples support many operations such as slicing, sorting, and reversing. Type the
following:
# Slicing
print(my_tuple[1:4])
# Sorting
sorted_tuple = sorted(my_tuple)
print(sorted_tuple)
# Reversing
reversed_tuple = my_tuple[::-1]
print(reversed_tuple)
a. Write a Python program to create a tuple of fruits and vegetables, and then slice the
tuple to print only the fruits.
b. Write a Python program to create a tuple of numbers and find the sum of all the
elements in the tuple.
c. Write a Python program to create a tuple of strings and sort them in alphabetical
order.
d. Write a Python program to create a tuple of names and check if a particular name is
present in the tuple.
e. Write a Python program to create two tuples and concatenate them into a single
tuple.