UNIT-02 STRING , LIST & TUPLES
UNIT-02 STRING , LIST & TUPLES
TUPLES
UNIT 02
A list is created using square brackets. At its simplest, a list is
simply a collection of values, separated by commas:
sum = 0.0
Example count = 0
num = input(“enter your
Program : number:”)
while num != -1:
Finding sum = sum + num
count = count + 1
Average num = input(“enter your
and number:”)
print “average is “, sum / count
Standard Finally, the standard deviation is the square root of
Deviation the resulting sum.
std dev = sqrt (summation (xi – ave)2 /
n)
Let us rewrite the program so that it first places all the elements into a list, then uses
functions to compute the different statistics.
import Math
def std (data, ave):
# compute standard deviation of values from average
diffs = 0.0
for x in data:
xdiff = x – ave # compute difference from average
diffs = diffs + xdiff * xdiff # squared
if len(data) == 0: return 0
else:
return Math.sqrt(diffs/len(data))
There are times when you want to create a fixed size list, but you
will not know until later what values will be stored in the list.
Such an object is similar to an array in other programming
languages.
The typical Python solution is to use the repetition operator and a
Fixed size list containing the value None:
lists are >>> a = [None]*5
Arrays >>> a
[None, None, None,
None, None]
A two dimensional array is usually represented in Python by a list
of lists.
However, the initialization of such a value is not as easy as the
initialization of a one-dimensional list.
Here is an example that illustrates the most common technique.
>>> range(1,
6)
[1, 2, 3, 4, 5]
Lists and The for statement can be used with any list. Elements
Loops are examined one by one, assigned to the loop
variable, and the body of the loop is executed.
>>> lst = [3, 5,
7]
>>> for x in lst:
print x
3
5
7
An interesting function named zip takes two lists, and produces
a list of tuples representing their pairs:
s >>> a = [1, 2, 3]
>>> b = a
>>> b[1] = 7
>>> a
[1, 7, 3]
>>> a = [1, 2, 3]
>>> b = a[:] # use a slice instead of a Sometimes you want to avoid the trap
simple name of reference assignment by making a
>>> b[1] = 7 true copy.
>>> a The easiest way to do this in Python is
[1, 2, 3] to use a slice, as in the following:
data = []
name = ‘’ def compareIndexOne
Example – while name != ‘done’: (x, y):
Sorted List name = raw_input(“enter name,
or ‘done’ to finish: ”)
# compare two lists
based on index value 1
of Names if name != ‘done’:
age = input(“enter age for “ +
if x[1] < y[1]: return -1
if x[1] == y[1]: return 0
and Ages name + “: “)
data.append([name, age])
return 1
data.sort(compareIndexOne)
for element in data:
print ‘name: ‘, element[0], ‘ age: ‘,
element[1]
A tuple is similar to a list, but is formed using parenthesis rather
than square brackets.
Like strings, tuples are immutable, meaning they cannot be changed
once they are created.
In all other respects they are identical to a list. This means that any
of the list operations that do not change the value of the tuple are
valid.
Tuples A list can be changed into a tuple, and vice versa.
Applicatio 'Jun',
'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
n – Date month, day, year = date.split('/')
return monthNames[eval(month)-1] + ' ' + day
Conversio + ', ' + year
>>> print longDate('4/1/2007')
n Apr 1, 2007
def encrypt (text):
result = ''
for c in text:
An result = result + ' ' + str(ord(c)) def decrypt (text):
return result result = ''
Example >>> hidden = encrypt(“Mike loves for num in text.split():
Applicatio mary”)
>>> print hidden
result = result +
chr(eval(num))
n– 77 105 107 101 32 108 111 118
101 115 32 109 97 114 121
return result
Encryption
def rot13char (c):
alphabet =
‘abcdefghijklmnopqrstuvwxyz’ The encoded string is now no longer than the original:
idx = alphabet.find( c )
idx = (idx + 13) % 26
return alphabet[idx] >>> print rot13(“I’m happy to
see this!”)
v'a unddm hc grr huvg!
def rot13 (s):
result = ''
for c in s.lower(): Even more important, two encodings return the
if 'a' <= c <= 'z': original string (albeit with all lower case
result = result + letters):
rot13char(c)
else: result = result + c >>> print rot13(rot13(“Rats live on no
return result evil star”))
rats live on no evil star
In addition to single and double quotes, strings can also be defined
Triple using triple quotes.
These are written using three single (‘’’) or double (“””) quote
Quoted marks.
String, Triple quoted strings can both span multiple lines and include
single or double quote marks
Raw >>> line = ‘’’Robin
strings said:
“don’t shoot!” just as
and the
rifle went off’’’
Escape >>> print line
Characters Robin said:
"don't shoot" just as
the
rifle went off
• String literals can also include escape characters. These are characters that are preceded
by a back slash.
• The backslash indicates that the following character is to be given a special meaning.
• Examples include \t for the tab character, \n for a newline character, \’ and \” for single and double quotes, and \\
for a backslash character itself. These can be used, for example, to create a string that includes both single and
double quote marks.
import shelve
A Telephone Database # telephone database application
# written by Tim Budd
An example program can import shelve
help illustrate the use of database = shelve.open("phoneinfo")
persistent variables. This print "Commands are whois, add, search
program will maintain a and quit"
telephone database line = raw_input("command: ")
while line != 'quit':
Commands to use the database will be the
words = line.split()
following:
if words[0] == 'whois':
whois phone-number
print words[1],":",database[words[1]]
# find the information associated with a number
elif words[0] == 'add':
add phone-number information
database[words[1]] = “ “.join(words[2:])
# will add information to the database search
elif words[0] == 'search':
keyword
for e in database.keys():
# find all the entries that include keyword quit
if database[e].find(words[1]) != -1:
# halt the application
A shelve named “phoneinfo” is used to store the print e,":",database[e]
telephone database. A loop reads commands from the line = raw_input("comand: ")
user database.close()