You are on page 1of 42

Dr. A.

Obulesh
Dept. of CSE
Touple

2
Tuples Are Like Lists
Tuples are another kind of sequence that functions much like a list
- they have elements which are indexed starting at 0
>>> x = ('Glenn', 'Sally', 'Joseph') >>> for iter in y:
>>> print(x[2]) ... print(iter)
Joseph ...
>>> y = ( 1, 9, 2 ) 1
>>> print(y) 9
(1, 9, 2) 2
>>> print(max(y)) >>>
9
but... Tuples are “immutable”
Unlike a list, once you create a tuple, you cannot alter its
contents - similar to a string

>>> x = [9, 8, 7]
>>> y = 'ABC' >>> z = (5, 4, 3)
>>> x[2] = 6
>>> y[2] = 'D' >>> z[2] = 0
>>> print(x)
Traceback:'str' object does Traceback:'tuple' object does
>>>[9, 8, 6]
not support item not support item
>>>
Assignment Assignment
>>> >>>
Things not to do With Tuples
>>> x = (3, 2, 1)
>>> x.sort()
Traceback:
AttributeError: 'tuple' object has no attribute 'sort'
>>> x.append(5)
Traceback:
AttributeError: 'tuple' object has no attribute 'append'
>>> x.reverse()
Traceback:
AttributeError: 'tuple' object has no attribute 'reverse'
>>>
A Tale of Two Sequences

>>> l = list()
>>> dir(l)
['append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

>>> t = tuple()
>>> dir(t)
['count', 'index']
Tuples are More Efficient
• Since Python does not have to build tuple structures to be
modifiable, they are simpler and more efficient in terms of
memory use and performance than lists
• So in our program when we are making “temporary variables”
we prefer tuples over lists
Tuples and Assignment
• We can also put a tuple on the left-hand side of an assignment
statement
• We can even omit the parentheses

>>> (x, y) = (4, 'fred')


>>> print(y)
fred
>>> (a, b) = (99, 98)
>>> print(a)
99
Tuples and Dictionaries
>>> d = dict()
>>> d['csev'] = 2
>>> d['cwen'] = 4
The items() method >>> for (k,v) in d.items():
in dictionaries ... print(k, v)
returns a list of (key, ...
value) tuples csev 2
cwen 4
>>> tups = d.items()
>>> print(tups)
dict_items([('csev', 2), ('cwen', 4)])
Tuples are Comparable
The comparison operators work with tuples and other
sequences. If the first item is equal, Python goes on to the next
element, and so on, until it finds elements that differ.
>>> (0, 1, 2) < (5, 1, 2)
True
>>> (0, 1, 2000000) < (0, 3, 4)
True
>>> ( 'Jones', 'Sally' ) < ('Jones', 'Sam')
True
>>> ( 'Jones', 'Sally') > ('Adams', 'Sam')
True
Sorting Lists of Tuples
• We can take advantage of the ability to sort a list of tuples to
get a sorted version of a dictionary
• First we sort the dictionary by the key using the items() method
and sorted() function

>>> d = {'a':10, 'b':1, 'c':22}


>>> d.items()
dict_items([('a', 10), ('c', 22), ('b', 1)])
>>> sorted(d.items())
[('a', 10), ('b', 1), ('c', 22)]
Using sorted()
>>> d = {'a':10, 'b':1, 'c':22}
We can do this even >>> t = sorted(d.items())
more directly using >>> t
[('a', 10), ('b', 1), ('c', 22)]
the built-in function
>>> for k, v in sorted(d.items()):
sorted that takes a ... print(k, v)
sequence as a ...
parameter and a 10
returns a sorted b1
sequence c 22
Sort by Values Instead of Key
• If we could construct a >>> c = {'a':10, 'b':1, 'c':22}
>>> tmp = list()
list of tuples of the
>>> for k, v in c.items() :
form (value, key) we ... tmp.append( (v, k) )
could sort by value ...
>>> print(tmp)
• We do this with a for [(10, 'a'), (22, 'c'), (1, 'b')]
loop that creates a list >>> tmp = sorted(tmp, reverse=True)
of tuples >>> print(tmp)
[(22, 'c'), (10, 'a'), (1, 'b')]
fhand = open('romeo.txt') The top 10 most
counts = {}
for line in fhand:
common words
words = line.split()
for word in words:
counts[word] = counts.get(word, 0 ) + 1

lst = []
for key, val in counts.items():
newtup = (val, key)
lst.append(newtup)

lst = sorted(lst, reverse=True)

for val, key in lst[:10] :


print(key, val)
Even Shorter Version
>>> c = {'a':10, 'b':1, 'c':22}

>>> print( sorted( [ (v,k) for k,v in c.items() ] ) )

[(1, 'b'), (10, 'a'), (22, 'c')]

List comprehension creates a dynamic list. In this case, we


make a list of reversed tuples and then sort it.
http://wiki.python.org/moin/HowTo/Sorting
Summary
• Tuple syntax • Tuples in assignment
• statements
Immutability
• Sorting dictionaries by
• Comparability
either key or value
• Sorting
Acknowledgements / Contributions
These slides are Copyright 2010- Charles R. Severance (
...
www.dr-chuck.com) of the University of Michigan School of
Information and open.umich.edu and made available under a
Creative Commons Attribution 4.0 License. Please maintain this
last slide in all copies of the document to comply with the
attribution requirements of the license. If you make a change, feel
free to add your name and organization to the list of contributors
on this page as you republish the materials.

Initial Development: Charles Severance, University of Michigan


School of Information

… Insert new Contributors and Translators here


Reading and >>> name = input('Enter:')

Converting Enter:Chuck
>>> print(name)
Chuck
• We prefer to read data in using >>> apple = input('Enter:')
strings and then parse and Enter:100
convert the data as we need >>> x = apple – 10
Traceback (most recent call last): File
• This gives us more control over "<stdin>", line 1, in <module>
error situations and/or bad user TypeError: unsupported operand type(s) for -:
input 'str' and 'int'
>>> x = int(apple) – 10
• Input numbers must be >>> print(x)
converted from strings 90
Looking Inside Strings
• We can get at any single character in a b a n a n a
string using an index specified in 0 1 2 3 4 5
square brackets
>>> fruit = 'banana'

• The index value must be an integer and >>> letter = fruit[1]


>>> print(letter)
starts at zero a
>>> x = 3
• The index value can be an expression >>> w = fruit[x - 1]
that is computed >>> print(w)
n
A Character Too Far
• You will get a python error
>>> zot = 'abc'
if you attempt to index
>>> print(zot[5])
beyond the end of a string Traceback (most recent call last): File
"<stdin>", line 1, in <module>
• So be careful when IndexError: string index out of range
constructing index values >>>
and slices
Strings Have Length

b a n a n a
The built-in function len gives 0 1 2 3 4 5
us the length of a string
>>> fruit = 'banana'
>>> print(len(fruit))
6
len Function
>>> fruit = 'banana' A function is some stored
>>> x = len(fruit) code that we use. A
>>> print(x) function takes some input
6 and produces an output.

'banana' len() 6
(a number)
(a string) function
len Function
>>> fruit = 'banana' A function is some stored
>>> x = len(fruit) code that we use. A
>>> print(x) function takes some input
6 and produces an output.

def len(inp):
blah
'banana' blah 6
for x in y: (a number)
(a string) blah
blah
Looping Through Strings

Using a while statement, fruit = 'banana' 0b


an iteration variable, and index = 0 1a
the len function, we can while index < len(fruit): 2n
construct a loop to look at letter = fruit[index] 3a
print(index, letter) 4n
each of the letters in a index = index + 1
string individually 5a
Looping Through Strings

• A definite loop using a for b


statement is much more a
elegant fruit = 'banana'
for letter in fruit: n
a
• The iteration variable is print(letter)
n
completely taken care of a
by the for loop
Looping Through Strings

• A definite loop using a fruit = 'banana'


for letter in fruit :
b
for statement is much a
print(letter)
more elegant n
a
• The iteration variable is index = 0 n
completely taken care of while index < len(fruit) :
a
by the for loop letter = fruit[index]
print(letter)
index = index + 1
Looping and Counting
word = 'banana'
This is a simple loop that count = 0
loops through each letter in a for letter in word :
string and counts the number if letter == 'a' :
of times the loop encounters count = count + 1
the 'a' character print(count)
Looking Deeper into in
• The iteration variable “iterates”
through the sequence Iteration Six-character
(ordered set) variable string
• The block (body) of code is
executed once for each value for letter in 'banana' :
in the sequence
print(letter)
• The iteration variable moves
through all of the values in the
sequence
Slicing Strings M o n t y P y t h o n
0 1 2 3 4 5 6 7 8 9 10 11
• We can also look at any
continuous section of a string
using a colon operator >>> s = 'Monty Python'
>>> print(s[0:4])
• The second number is one Mont
beyond the end of the slice - >>> print(s[6:7])
“up to but not including” P
• If the second number is >>> print(s[6:20])
beyond the end of the string, it Python
stops at the end
Slicing Strings M o n t y P y t h o n
0 1 2 3 4 5 6 7 8 9 10 11

>>> s = 'Monty Python'


If we leave off the first number >>> print(s[:2])
or the last number of the slice, Mo
it is assumed to be the >>> print(s[8:])
beginning or end of the string thon
respectively >>> print(s[:])
Monty Python
String Concatenation
>>> a = 'Hello'
>>> b = a + 'There'
When the + operator is >>> print(b)
applied to strings, it means HelloThere
“concatenation” >>> c = a + ' ' + 'There'
>>> print(c)
Hello There
>>>
Using in as a Logical Operator
>>> fruit = 'banana'

• The in keyword can also be


>>> 'n' in fruit
True
used to check to see if one >>> 'm' in fruit
string is “in” another string False
>>> 'nan' in fruit
• The in expression is a logical True
>>> if 'a' in fruit :
expression that returns True
or False and can be used in ... print('Found it!')
...
an if statement Found it!
>>>
String Comparison
if word == 'banana':
print('All right, bananas.')

if word < 'banana':


print('Your word,' + word + ', comes before banana.')
elif word > 'banana':
print('Your word,' + word + ', comes after banana.')
else:
print('All right, bananas.')
• Python has a number of string String Library
functions which are in the
string library
>>> greet = 'Hello Bob'
• These functions are already >>> zap = greet.lower()
built into every string - we >>> print(zap)
invoke them by appending the hello bob
function to the string variable >>> print(greet)
Hello Bob
• These functions do not modify >>> print('Hi There'.lower())
the original string, instead they hi there
return a new string that has >>>
been altered
>>> stuff = 'Hello world'
>>> type(stuff)
<class 'str'>
>>> dir(stuff)
['capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format',
'format_map', 'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric',
'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition',
'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip',
'swapcase', 'title', 'translate', 'upper', 'zfill']

https://docs.python.org/3/library/stdtypes.html#string-methods
String Library
str.capitalize() str.replace(old, new[, count])
str.center(width[, fillchar]) str.lower()
str.endswith(suffix[, start[, end]]) str.rstrip([chars])
str.find(sub[, start[, end]]) str.strip([chars])
str.lstrip([chars]) str.upper()
Searching a String
b a n a n a
• We use the find() function to search
for a substring within another string
0 1 2 3 4 5

• find() finds the first occurrence of the >>> fruit = 'banana'


substring >>> pos = fruit.find('na')
>>> print(pos)
• If the substring is not found, find() 2
returns -1 >>> aa = fruit.find('z')
>>> print(aa)
• Remember that string position starts -1
at zero
Making everything UPPER CASE

• You can make a copy of a >>> greet = 'Hello Bob'


string in lower case or upper >>> nnn = greet.upper()
case >>> print(nnn)
• Often when we are searching
HELLO BOB
>>> www = greet.lower()
for a string using find() we first
>>> print(www)
convert the string to lower case
hello bob
so we can search a string
>>>
regardless of case
Search and Replace
• The replace() function
is like a “search and >>> greet = 'Hello Bob'
replace” operation in a >>> nstr = greet.replace('Bob','Jane')
>>> print(nstr)
word processor
Hello Jane

• It replaces all
>>> nstr = greet.replace('o','X')
>>> print(nstr)
occurrences of the HellX BXb
search string with the >>>
replacement string
Stripping Whitespace
• Sometimes we want to take a
string and remove
whitespace at the beginning >>> greet = ' Hello Bob '
and/or end >>> greet.lstrip()
'Hello Bob '

• lstrip() and rstrip() remove


>>> greet.rstrip()
' Hello Bob'
whitespace at the left or right >>> greet.strip()
'Hello Bob'
• strip() removes both >>>
beginning and ending
whitespace
Prefixes
>>> line = 'Please have a nice day'
>>> line.startswith('Please')
True
>>> line.startswith('p')
False

You might also like