Data Structure: Tuple
Data Structure: Tuple
You may walk through this program to understand the creation and the
operations on a tuple.
If the element of a tuple is a list, then the list can be modifed by adding
elements or removing them. We cannot replace the element of the tuple by
assignment even if it is a list.
Creation of tuple:
• empty tuple
◦ t1 = ()
◦ t2 = tuple()
• two element tuple
◦ t3 = (1, 2)
• one element tuple
◦ t4 = (10) # NO
◦ t5 = (20,) # Yes
There is an ambiguity when we use parentheses around a single expression.
Should we consider this as an expression or a tuple? The language considers
this as an expression. To make a tuple of single element, we require an extra
comma.
# name : 1_tuple.py
# tuple
# is a sequence
# like a list
# indexed by int; leftmost element has an index 0
# select the element using []
# is immutable
# once created, cannot be changed
# length of the tuple cannot change
# heterogeneous
# iterable
a = (11, 33, 22, 44, 55)
print(a)
print(a[2]) # 22
print(a[2:4]) # (22, 44)
#a[2] = 222 # NO
#a.append(66) # Error
b[0].append(67) #ok
#b[0] = [78, 89] #no
#del b[0] # no
#b[0] += [100] # no ; assignment forbidden
for i in [c] :
print("two") # once
# name: 2_tuple.py
a = 1, 2, 3
print(a, type(a))
x, y, z = a
print(x, y, z)
#q, w = a # error; # of variables on the left should match the # of elem in the
tuple
#-----------------
score = { }
#score['gavaskar'] = 10000
# many times, key has components : composite key
# should be immutable; cannot be a list
#score[['sunil', 'gavaskar']] = 10000 # NO
#score[['rohan', 'gavaskar']] = 1000 # NO
Tuples are also used as keys of dict whenever the key has multiple components
– key of the dict is a composite. The key of a dict should be immutable. So the
key cannot be a list, but it can be a tuple.
d) raw strings
There are cases where the escape sequence should not be expanded – we
require such strings as patterns in pattern matching using regular expressions.
In such cases, we prefx r to the string literal – it becomes a raw string.
# name : str3.py
"""
this program
is about playing
with strings
"""
# stored in a variable : __doc__
# strings
# sequence
# indexed
# leftmost index : 0
# immutable
# no character type
# can be sliced
# cannot assign
a = "rose"
print(a, type(a), a[2], type(a[2]))
#a[0] = 'b' # error
# make a string:
# 1. single quotes
# 2. double quotes
# no diference between them
# escape sequences are expanded
s1 = "this is a \n string"
s2 = 'this is a \n string'
print(s1, type(s1))
print(s2, type(s2))
# 3. raw string
# no escaping
s3 = r"this is a \n string"
print(s3, type(s3))
The following example shows how to play with the strings. The str type has lots
of useful functions.
• Build a string in stages
ss = “” # create an empty string
ss = ss + “something” # create a new string by concatenation
• call some utility function like upper or replace
x = “abcd”; x.upper(); print(x)
We will observe that x has not changed. Remember that x is immutable.
In case we want the original string to change, assign the result of the
function call back to the same variable – thus recreating the variable.
x = “abcd”; x = x.upper(); print(x)
• Observe that replace will return a new string modifying every
occurrences of the old string with the replace string. We can control the
number of changes by using a count as the third argument.
• Index fnds the leftmost occurrence of a substring in the given string.
Finding the nth occurrence or replacing the nth occurrence become
programming exercises.
# name : 4_str.py
"""
s = 'mohanDas Karamchand gandhi'
# print "m K gandhi"
# make a list of words by splitting
# output the frst char of each word but for the last; output the last word
ss = ''
namelist = s.split()
for name in namelist[:len(namelist)-1]:
#print(name[0])
ss = ss + name[0] + " "
#print(namelist[-1]) # last elem
ss = ss + namelist[-1]
print(ss)
#ss.upper() # NO; does not change the str; returns a new changed string
ss = ss.upper()
print(ss)
ss = ss.title()
print(ss)
s = s.title()
print(s)
"""
mylist = [
"indira gandhi",
"m k gandhi",
"rahul gandhi",
"jawaharlal nehru",
"sardar patel",
"brijesh patel"
]
for w in mylist :
if w.endswith('gandhi') :
print(w)
# name: 5_str.py
s = "we love python very much"
for w in s.split():
print(w[1:], end = "")
print(w[0], end = " ")
print()
for ch in s:
print(ch, end = "")
print('p', end = "")
print()
Outputs are:
ew ovel ythonp eryv uchm
wpep plpopvpep pppyptphpopnp pvpeprpyp pmpupcphp