Lecture 7a
Lecture 7a
1
4/17/2023
LEARNING OUTCOMES
WHAT IS TUPLE?
A tuple is a sequence of values, which can be of any type and they
are indexed by integer. Tuples are just like list, but we can’t change values
of tuples in place. Thus, tuples are immutable.
The index value of tuple starts from 0.
2
4/17/2023
ACCESSING TUPLE
3
4/17/2023
OUTPUT
4
4/17/2023
OUTPUT
9
TUPLE LENGTH
OUTPUT
10
5
4/17/2023
REMOVING A TUPLE
11
TUPLE METHODS
12
6
4/17/2023
TUPLE METHODS
Python provides two built-in methods that you can use on tuples.
1. count() Method
2. index() Method
13
TUPLE METHODS
1. count() Method
Return the
number of times the
value appears in the
tuple
14
7
4/17/2023
TUPLE METHODS
2. index() Method
index()
Method
15
16
8
4/17/2023
Tuple
17
18
9
4/17/2023
19
20
10
4/17/2023
List uses [ and ] (square brackets) to Tuple uses rounded brackets ( and
bind the elements. ) to bind the elements.
21
LIST TUPLE
List can be edited once it is created A tuple is a list which one cannot edit
in python. Lists are mutable data once it is created in Python code. The
structure. tuple is an immutable data structure
22
11
4/17/2023
TUPLE DICTIONARY
Order is maintained. Ordering is not guaranteed.
They can hold any type, and types Every entry has a key and a value
can be mixed.
23
24
12
4/17/2023
PROGRAMS ON
TUPLE
25
26
13
4/17/2023
27
28
14
4/17/2023
29
#create a tuple
tuplex = tuple("index tuple")
print(tuplex)
#get index of the first item whose value is passed as parameter
index = tuplex.index("e")
print("index of e is ", index)
#define the index from which you want to search
index = tuplex.index("e",5)
print("index of e in range from 5 to end is ", index)
30
15
4/17/2023
31
print(index)
#define the segment of the tuple to be searched
index = tuplex.index("e", 3, 6)
print(index)
#if item not exists in the tuple return ValueError Exception
index = tuplex.index("y")
32
16
4/17/2023
33
34
17
4/17/2023
35
36
18
4/17/2023
37
38
19
4/17/2023
7. Write a Python program to get the 4th element and 4th element from last
of a tuple.
39
40
20
4/17/2023
41
#create a tuple
tuplex = 2, 4, 5, 6, 2, 3, 4, 4, 7
print(tuplex)
#return the number of times it appears in the tuple.
count = tuplex.count(4) print(count)
42
21
4/17/2023
43
44
22