0% found this document useful (0 votes)
16 views38 pages

UNIT-02 STRING , LIST & TUPLES

This document provides an overview of lists and tuples in Python, highlighting their creation, mutability, and operations such as appending, extending, and sorting. It also discusses the concept of references, equality, and identity in relation to lists, as well as the use of tuples for encapsulating multiple arguments. Additionally, the document includes examples of functions for calculating averages and standard deviations, as well as string formatting and encryption techniques.

Uploaded by

Gavi Kiran
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views38 pages

UNIT-02 STRING , LIST & TUPLES

This document provides an overview of lists and tuples in Python, highlighting their creation, mutability, and operations such as appending, extending, and sorting. It also discusses the concept of references, equality, and identity in relation to lists, as well as the use of tuples for encapsulating multiple arguments. Additionally, the document includes examples of functions for calculating averages and standard deviations, as well as string formatting and encryption techniques.

Uploaded by

Gavi Kiran
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 38

STRING , LISTS &

TUPLES
UNIT 02
 A list is created using square brackets. At its simplest, a list is
simply a collection of values, separated by commas:

>>> lst = [1, 4, 7, 9, 12] # create a list with five elements


>>> lst
LISTS [1, 4, 7, 9, 12]

 Unlike a string, a list is mutable. This means that the elements in a


list can be changed after it is created.
LIST
OPERATIO
NS
 The end of the list was indicated by the value -1

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.

def main (): # use the main program convention


# program to compute average, standard dev of list of numbers
print “enter values to be analyzed, use -1 to end list”
data = [ ] # our list of values
num = input(“enter your number:”)
while num != -1:
data.append(num) # add value to data list
num = input(“enter our number:”)
ave = average(data)
print ‘average of data values is ‘, ave
std = std(data, ave)
print ‘standard deviation is ‘, std
The range function used in earlier chapter constructed a list, and the for statement was
used to iterate over the elements of the list:
So the function average can be written as follows:

def average (data):


# compute average of a list of numbers Since lists can be indexed, an
sum = 0.0 # make sum into a floating point alternative way to write the loop
number would have been to loop
for x in data: over the set of index values, as
sum = sum + x follows:
if len(data) == 0: return 0
else:
for i in range(0, len(data)):
return sum / len(data)
sum = sum + data[i]
Or even to use a while
loop:
i = 0
while (i < len(data)):
sum = sum + data[i]
i = i + 1
The function to compute the standard deviation uses sqrt from the Math module. So
we
need to remember to import this module in the program somewhere before the
function is
defined

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.

>>> data = [None] * 5


>>> for i in range(0,5):
... data[i] = [0] * 5
...
>>> data
[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0,
0, 0],
[0, 0, 0, 0, 0]]
>>> data[2][2] = 7
>>> data
[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 7, 0, 0], [0, 0, 0,
0, 0],
[0, 0, 0, 0, 0]]
 Note carefully that append and extend work by side effect, altering
the list to the left of the dot. The value these functions return is the
constant None.
>>> lst = [1, 2, 3]
>>> print
Append lst.append(4)
None
works by  A common beginners mistake is to reassign the value returned by
side effect this function to the list variable. The student is then surprised at the
result.
>>> lst = [1, 2, 3]
>>> lst =
lst.append(4)
>>> print lst
None
 The range function can be used with the for statement to loop over
an arithmetic progression.
 In fact, range is simply a function that produces a list of values:

>>> 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:

>>> zip([1, 2, 3],


[5, 6, 7])
[(1, 5), (2, 6), (3, 7)]
When combined with the multiple assignment, this
produces an easy and elegant way to loop over two
lists in parallel:
>>> one = [1, 2, 3]
>>> two = [5, 6, 7]
>>> for x, y in zip(one,
two):
… print ‘x’, x,’and y’,y
x 1 and y 5
x 2 and y 6
x 3 and y 7
 Now that we have a mutable data type we can discuss a subtle but
nevertheless very important concept.
 This is the idea of references, and in particular the fact that
assignment copies references and not values.
 Imagine that we create a list and assign it to a variable named a.
Assignmen Next we assign the variable a to another variable b.
t and  Finally we make a change to part of b. What do you think will be
Reference the value being held in a?

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:

def sneaky (n):


n[1] = ‘a’ The function changes one of
>>> a = [1, 2, 3] the fields in the argument
>>> sneaky(a) value. You can see this by
>>> a passing a list, and looking at
[1, ‘a’, 3] the result after the function
call.
 The operator you have seen, ==, is testing equality.
 The identity testing operator is called is.
 Two lists are equal if they are the same length and their corresponding
elements are equal.
 Two lists are identical if they are exactly the same object.

Identity >>> if [1, 2, 3] == [1, 2, 3]:


print ‘equal’
and equal
>>> if [1, 2, 3] is [1, 2, 3]: print
Equality ‘identical’
>>>

 The two lists are equal, but not identical.


 On the other hand, if you assign a value stored in one
variable to another variable, then the values held by
the two variables are both identical and equal:
>>> a = [1, 2, 3]
>>> b = a
>>> if a is b: print
‘identical’
identical
 Use the identity testing operator, is, if you need to
determine if two variables hold exactly the same
object.
 Use the equality operator, ==, if you simply need to
know if they have same value, even if they are not
the same object.
 A sorted list is a list in which the elements appear in order. This is
frequently needed when producing output
 for example to print string values in alphabetical order.
 There are two major ways to produce a sorted list. T
 he built-in function named sorted will produce a sorted version of a
Sorted list:

Lists def smallerThan(x,


y):
>>> lst = [4, 2,
>>> sorted([4, 2, 6, 6, 3, 1] if x < y: return 1
3, 1]) >>> lst.sort() if x == y: return 0
[1, 2, 3, 4, 6] >>> lst return -1
[1, 2, 3, 4, 6] >>>
lst.sort(smallerThan)
>>> lst
[6, 4, 3, 2, 1]
[[‘fred smith’, 42], [‘robin jones’, 38], [‘alice
johnson’, 29]]

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.

>>> tup = (1, 2, 3, 2, 1)


>>> 2 in tup
True
>>> list(tup)
[1, 2, 3, 2, 1]
>>> tuple([‘a’, ‘b’, ‘c’])
(‘a’, ‘b’, ‘c’)
>>> tuple(‘abc’)
(‘a’, ‘b’, ‘c’)
 Tuples are sometimes used to encapsulate an indefinite (or variable)
number of arguments, so that a function or operator can deal with
just a single entity.
 An example is the string formatting operator, written %.
experiment with this operator you might have been confused by an
Tuples and odd error message:

String >>> "abc" % 'def'


Traceback (most recent call last):
Formattin File "<stdin>", line 1, in ?
TypeError: not all arguments converted
g during string formatting
 Here is a more proper example of the use of this
operator:
>>> 'int %d float %g and string %s' % (17,
3.14, "abc")
'int 17 float 3.14 and string abc'
String
Functions
def isLetter ( c ):
# return true if c is a letter
def palTest (s):
return (‘a’ <= c <= ‘z’) or (‘A’
if len(s) <= 1: return True
An elif s[0] != s[-1] : return
<= c <= ‘Z’)
def palTest (s):
False
Example else: return
if len(s) <= 1: return True
elif not isLetter(s[0]): return
Applicatio palTest(s[1:len(s)-1])
>>> print palTest(“rotor”)
palTest(s[1:])
elif not isLetter(s[-1]): return
n– True
>>> print
palTest(s[:-1])
Palindrom palTest(“refried”)
False
elif s[0].lower() != s[-
1].lower(): return False
e Testing >>> print palTest(“rats
else: return palTest(s[1:len(s)-
1])
live on no evil star”)
>>> print palTest(“A man, a
True
plan, a canal, Panama!”)
True
An
def longDate (date):
Example monthNames = ['Jan', 'Feb', 'Mar', 'Apr', 'May',

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.

>>> line = “she replied: \”I didn’t mean


to do it!\” “ >>> print r'red\nbeans\nand\
>>> line nrice'
she replied: " I didn't mean to do it!" red\nbeans\nand\nrice

Finally, raw strings turn off the


processing of escape sequences.
>>> print “red\n beans\n and\n rice”
This is useful when you want to
red
create a string that contains
beans
many backslash characters. A
and
raw string is preceded by the
rice
character r
The newline character produces a carriage
return when it is printed
 A dictionary is an indexed data structure, and uses the same square
bracket syntax for indexing as a list.
 But in a dictionary
>>> the
dctindices
= { } are
# create
not positions, but values.
a new dictionary
Dictionarie >>> dct[‘name’] =
‘chris smith’
s >>> dct[‘age’] = 27
>>> dct[‘eyes’] = ‘blue’

 The index expression is termed a key, while the element stored in


association with the key is termed a value. Dictionaries are also some
times termed maps, hashes or associative arrays
>>> print dct['name']
chris smith As with a list, the function len can be used to
>>> print dct.get(‘age’) determine the number of elements (the length) of the
27 dictionary. Also the del function can be used to delete
>>> print dct['weight'] an element from a dictionary.
Traceback (most recent call last):
File "<stdin>", line 1, in ?
KeyError: 'weight' >>> del dct[‘age’]
>>> print dct.get('weight', 0) # use 0 as >>> print dct[‘age’]
default value Traceback (most recent call
0 last):
>>> dct[‘age’] = 28 # change the value File "<stdin>", line 1, in ?
>>> dct[‘age’] KeyError: ‘age’
28
The most
common
operations
for a
dictionary
are shown
in
the table
Example: Counting Elements def main ():
freq = { }
def frequency (lst): line = raw_input()
counts = { } while line != ‘quit’:
for ele in lst: words = line.split()
counts[ele] = counts.get(ele, 0) + 1 for word in words:
return counts freq[word] = freq.get(word, 0) + 1
>>> frequency([‘abc’, ‘def’, ‘abc’, line = raw_input()
‘pdq’, ‘abc’]) # now all words have been read
{'abc': 3, 'pdq': 1, 'def': 1} for word in freq:
print word + ‘ occurs ‘+ freq[word] + ‘
times’

Let us use this idea to write a


OUTPUT:
program that reads lines of text INPUT:
from the input until a line with the
of occurs 2 times
single word ‘quit’ is entered. After it was the best of
it occurs 2 times
each line is read it is split into times
times occurs 2 times
individual words, and a frequency it was the worst of
worst occurs 1 times
count is kept of each word. Once the times
the occurs 2 times
terminating line is found the quit
was occurs 2 times
frequency of each word is reported.
best occurs 1 times
 Two lists can be combined using catenation, or append. This
concept does not make sense for dictionaries, however a somewhat
similar operation is provided by the update method.
 This method takes as argument another dictionary.
Combining  The values from the argument dictionary are copied into the
two receiver, possibly overwriting an existing entry.
dictionarie >>> dictone = {'abc':3,
s with 'def':7, 'xyz': 9}

update >>> dicttwo = {'def':5,


'pdq': 4}
>>>
dictone.update(dicttwo)
>>> print dictone
{'xyz': 9, 'abc': 3, 'pdq': 4,
'def': 5}
Making Copies
Hence both refer to the same value. A
Remember that Python uses reference semantics from change to the dictionary inside the
assignment. If you simply assign one dictionary to a new function will remain after the function
variable, they end up referring to the same collection. A change returns.
to one will end up modifying both:
def sneaky (d):
>>> dictone = {'abc': 3, 'def': 7} d[‘ha’] = ‘ho’
>>> dicttwo = dictone >>> a = {‘one’:1, ‘two’: 2}
>>> dicttwo['xyz'] = 12
>>> sneaky(a)
>>> print dictone
{'xyz': 12, 'abc': 3, 'def': 7} >>> print a
{‘one’:1, ‘two’:2, ‘ha’:’ho’}
To make an independent copy of a dictionary you can use the
method copy.
>>> dictone = {'abc': 3, 'def': 7} Sometimes, having the function fill in values
>>> dicttow = dictone.copy()
in the dictionary is the behavior you
>>> dicttwo['xyz'] = 12
>>> print dictone want.Other times it is a sign of error. If you
{'abc': 3, 'def': 7} find a dictionary holding strange values one
possibility is to make copies of the dictionary
before passing it into any function, in case
When a dictionary is passed as an argument the parameter is the function is mistakenly filling in new
simply assigned the argument value. values.
Zip List Initialization

The function dict takes a list of two-


element tuples, and converts them
into a dictionary with the first
element in each tuple representing
This might at first not seem particularly useful,
the key and the second
since the dictionary literal is so much easier.
representing the value
But remember the function zip? Many times you
>>> x = dict([(‘name’, ‘fred’), will find yourself with a list of keys, and
(‘age’, 42), (‘weight’,175)]) separately with a list of values. Zip makes it
>>> x easy to convert this into a list of tuples, which
{‘name’:’fred’, ‘age’:42, can then be used to create a dictionary
‘weight’:175}
>>> keys =
[‘name’,’age’,’weight’]
>>> values = [‘fred’,42,175]
>>> x= dict(zip(keys, values))
>>> x
{‘name’:’fred’, ‘age’:42,
‘weight’:175}
Loops

Just as a for statement can be used to loop over


the elements in a list, a for can also be used to The order the elements are stored in a
cycle through the values in a dictionary. If you dictionary is purposely undefined, and
simply use the dictionary as the target of the for may even change during the course of
statement, the values returned are the keys for execution. Often you want to examine
the collection: the elements in a
particular sequence, for example in
>>> for e in info:
… print e ascending order of keys. This can be
‘name’ accomplished by
‘age’ sorting the list returned by the keys
‘weight’
operation:
Sometimes (actually, rarely) you want to iterate
for e in sorted(info.keys()): # cycle
over the set of values. This can be done using through keys in sorted order
the function values():

>>> for e in info.values():


… print e
‘fred’
42
175
Example - A Concordance
from string import split
• concordance is an alphabetical listing of the def countWords (words, dct,
words in a text, along with the line numbers on lineNumber):
which each word occurs. # update dictionary for each word
• A dictionary is a natural data structure for # with line number
representing a concordance. for word in words:
• The words in the text will be used as a key, lst = dct.get(word, [])
while the value will be the line numbers on lst.append(lineNumber)
which the word appears. dct[word] = lst
# step 1, read lines until finished
OUTPUT: line = raw_input()
$ python concordance.py lineNumber = 0
it was the best of times dct = { }
it was the worst of times while line != 'quit':
quit lineNumber += 1
best : [1] countWords(split(line), dct,
it : [1, 2] lineNumber)
of : [1, 2] line = raw_input()
the : [1, 2] # step 2, print results
times : [1, 2] for w in sorted(dict.keys()):
was : [1, 2] print w, ':', dct[w]
worst : [2]
Persistent Variables
• A persistent variable is a variable that
can retain its value across multiple
import shelve
executions.
data = shelve.open(“information”) # file is named
• Behind the scenes, such values are
information
stored in a file,. However, the user can
data[‘name’] = ‘fred smith’ # put information into
make use of the persistence facilities
shelve
without needing to use explicit file
print data[‘name’] # get information out of shelve
commands.
data.close() # close the shelf before quitting
• The easiest facility for providing
object persistence is the shelve
module.
• This can be imported using the
statement

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()

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy