Python Unit 2
Python Unit 2
Dr. Anand M
Assistant Professor
Python Lists
What is Not a “Collection”?
Most of our variables have one value in them - when we put a new
value in the variable, the old value is overwritten
$ python
>>> x = 2
>>> x = 4
>>> print(x)
4
A List is a Kind of
Collection
• A collection allows us to put many values in a single “variable”
5
for i in [5, 4, 3, 2, 1] :
print(i)
4
print('Blastoff!') 3
2
1
Blastoff!
Lists and Definite Loops - Best Pals
Just like strings, we can get at any single element in a list using an
index specified in square brackets
http://docs.python.org/tutorial/datastructures.html
Building a List from Scratch
• Python provides two operators >>> some = [1, 9, 21, 10, 16]
that let you check if an item is >>> 9 in some
in a list True
>>> 15 in some
False
• These are logical operators >>> 20 not in some
that return True or False True
>>>
• They do not modify the list
Lists are in Order
• A list can hold many
items and keeps
those items in the
order until we do >>> friends = [ 'Joseph', 'Glenn', 'Sally' ]
>>> friends.sort()
something to change >>> print(friends)
the order ['Glenn', 'Joseph', 'Sally']
>>> print(friends[1])
• A list can be sorted Joseph
(i.e., change its order) >>>
OUTPUT
CHECK IF ITEM EXISTS
OUTPUT
TUPLE LENGTH
OUTPUT
REMOVING A TUPLE
1. count() Method
2. index() Method
TUPLE METHODS
1. count() Method
Return the number of times the value appears in the tuple
Count() method
returns total no
times ‘banana’
present in the
given tuple
TUPLE METHODS
2. index() Method
index()
Method
Weekdays=[‘Sun’,’Mon’,’,
Weekdays=[‘Sun’,’Mon twdays = (‘Sun’, ‘mon
mon',', ‘tue
tue',', 634
634))
‘wed’,46
‘wed’, 46,,67]
67] type(twdays
type(twdays))
type(Weekdays) class<‘tuple’>
class<‘lists’>
List uses [ and ] (square brackets) Tuple uses rounded brackets( and ) to
to bind the elements
elements.. bind the elements.
elements.
DIFFERENCE BETWEEN LIST AND TUPLE
LIST TUPLE
List can be edited once it is A tuple is a list which one cannot edit
created in python
python.. Lists are once it is created in Python code.
code. The
mutable data structure.
structure. tuple is an immutable data structure
TUPLE DICTIONARY
Order is maintained
maintained.. Ordering is not guaranteed
guaranteed..
They can hold any type, and types Every entry has a key and a value
can be mixed
mixed..
DIFFERENCE BETWEEN TUPLE AND DICTIONARY
TUPLE DICTIONARY
Elements are accessed via Elements are accessed using key's
numeric (zero based) indices values
#create a tuple
tuplex = tuple("index tuple")
print(tuplex
print(tuplex))
#get index of the first item whose value is passed as parameter
index = tuplex.index("p")
tuplex.index("p")
print(index)
#define the index from which you want to search
index = tuplex.index("p",
tuplex.index("p", 5)
TUPLE - AVERAGE PROGRAMS
print(index)
#define the segment of the tuple to be searched
index = tuplex.index("e",
tuplex.index("e", 3, 6)
print(index)
#if item not exists in the tuple return ValueError Exception
index = tuplex.index
tuplex.index("y")
("y")
Python - Strings
• Strings are amongst the most popular types in Python. We can create them simply by enclosing
characters in quotes. Python treats single quotes the same as double quotes.
• Creating strings is as simple as assigning a value to a variable. For example:
var1 = 'Hello World!'
var2 = "Python Programming"
Accessing Values in Strings:
• Python does not support a character type; these are treated as strings of length one, thus also considered a
substring.
• To access substrings, use the square brackets for slicing along with the index or indices to obtain your substring:
• Example:
var 1 = 'Hello World!'
var2 = "Python Programming"
print "var1[0]: ", var1[0]
print "var2[1:5]: ", var2[1:5]
[] Slice - Gives the character from the given index a[1] will give e
[:] Range Slice - Gives the characters from the given a[1:4] will give ell
range
in Membership - Returns true if a character exists in H in a will give 1
the given string
not in Membership - Returns true if a character does not M not in a will give 1
exist in the given string
r/R Raw String - Suppress actual meaning of Escape print r'\n' prints \n and print
characters. R'\n' prints \n
% Format - Performs String formatting See at next section
String Formatting Operator:
Format Symbol Conversion
%c character
%s string conversion via str() prior to formatting
%i signed decimal integer
%d signed decimal integer
%u unsigned decimal integer
%o octal integer
%x hexadecimal integer (lowercase letters)
%X hexadecimal integer (UPPERcase letters)
%e exponential notation (with lowercase 'e')
%E exponential notation (with UPPERcase 'E')
%f floating point real number
%g the shorter of %f and %e
%G the shorter of %f and %E
Other supported symbols and functionality are listed in the following table:
Symbol Functionality
* argument specifies width or precision
- left justification
# add the octal leading zero ( '0' ) or hexadecimal leading '0x' or '0X', depending
on whether 'x' or 'X' were used.
0 pad from left with zeros (instead of spaces)
m.n. m is the minimum total width and n is the number of digits to display after the
decimal point (if appl.)
Triple Quotes:
• Python's triple quotes comes to the rescue by allowing strings to span multiple lines, including
verbatim NEWLINEs, TABs, and any other special characters.
• The syntax for triple quotes consists of three consecutive single or double quotes.
para_str = """this is a long string that is made up of several
lines and non-printable characters such as TAB ( \t ) and they
will show up that way when displayed. NEWLINEs within the string,
whether explicitly given like this within the brackets [ \n ], or
just a NEWLINE within the variable assignment will also show up.
"""
print para_str;
Raw String:
• Raw strings don't treat the backslash as a special character at all. Every character
you put into a raw string stays the way you wrote it:
print 'C:\\nowhere'
This would print following result:
C:\nowhere
Now let's make use of raw string. We would put expression in r'expression' as follows:
print r'C:\\nowhere'
This would print following result:
C:\\nowhere
Unicode String:
• Normal strings in Python are stored internally as 8-bit ASCII, while Unicode strings are stored as 16-
bit Unicode. This allows for a more varied set of characters, including special characters from most
languages in the world. I'll restrict my treatment of Unicode strings to the following:
print u'Hello, world!'
This would print following result:
Hello, world!
Built-in String Methods:
1 capitalize()
Capitalizes first letter of string
2 center(width, fillchar)
Returns a space-padded string with the original string centered to a total of width columns
4 encode(encoding='UTF-8',errors='strict')
Returns encoded string version of string; on error, default is to raise a ValueError unless errors is given with
'ignore' or 'replace'.
5 endswith(suffix, beg=0, end=len(string))
Determines if string or a substring of string (if starting index beg and ending index end are given) ends with
suffix; Returns true if so, and false otherwise
6 expandtabs(tabsize=8)
Expands tabs in string to multiple spaces; defaults to 8 spaces per tab if tabsize not provided
7 find(str, beg=0 end=len(string))
Determine if str occurs in string, or in a substring of string if starting index beg and ending index end are given;
returns index if found and -1 otherwise
8 index(str, beg=0, end=len(string))
9 isa1num()
Returns true if string has at least 1 character and all characters are alphanumeric and false otherwise
10 isalpha()
Returns true if string has at least 1 character and all characters are alphabetic and false otherwise
11 isdigit()
12 islower()
Returns true if string has at least 1 cased character and all cased characters are in lowercase and false otherwise
13 isnumeric()
Returns true if a unicode string contains only numeric characters and false otherwise
14 isspace()
Returns true if string contains only whitespace characters and false otherwise
15 istitle()
Returns true if string is properly "titlecased" and false otherwise
16 isupper()
Returns true if string has at least one cased character and all cased characters are in uppercase and false
otherwise
17 join(seq)
Merges (concatenates) the string representations of elements in sequence seq into a string, with separator string
18 len(string)
Returns the length of the string
19 ljust(width[, fillchar])
Returns a space-padded string with the original string left-justified to a total of width columns
20 lower()
Converts all uppercase letters in string to lowercase
21 lstrip()
Removes all leading whitespace in string
22 maketrans()
Returns a translation table to be used in translate function.
23 max(str)
Returns the max alphabetical character from the string str
24 min(str)
Replaces all occurrences of old in string with new, or at most max occurrences if max given
26 rfind(str, beg=0,end=len(string))
28 rjust(width,[, fillchar])
Returns a space-padded string with the original string right-justified to a total of width columns.
29 rstrip()
30 split(str="", num=string.count(str))
Splits string according to delimiter str (space if not provided) and returns list of substrings; split into at most num
substrings if given
31 splitlines( num=string.count('\n'))
Splits string at all (or num) NEWLINEs and returns a list of each line with NEWLINEs removed
32 startswith(str, beg=0,end=len(string))
Determines if string or a substring of string (if starting index beg and ending index end are given) starts with
substring str; Returns true if so, and false otherwise
33 strip([chars])
34 swapcase()
35 title()
Returns "titlecased" version of string, that is, all words begin with uppercase, and the rest are lowercase
36 translate(table, deletechars="")
Translates string according to translation table str(256 chars), removing those in the del string
37 upper()
38 zfill (width)
Returns original string leftpadded with zeros to a total of width characters; intended for numbers, zfill() retains
any sign given (less one zero)
39 isdecimal()
Returns true if a unicode string contains only decimal characters and false otherwise
Python - Dictionary
• A dictionary is mutable and is another container type that can store any number of Python objects, including
other container types.
• Dictionaries consist of pairs (called items) of keys and their corresponding values.
• Python dictionaries are also known as associative arrays or hash tables. The general syntax of a dictionary is as
follows:
dict = {'Alice': '2341', 'Beth': '9102', 'Cecil': '3258'}
• You can create dictionary in the following way as well:
dict1 = { 'abc': 456 };
dict2 = { 'abc': 123, 98.6: 37 };
• Each key is separated from its value by a colon (:), the items are separated by commas, and the whole thing is
enclosed in curly braces. An empty dictionary without any items is written with just two curly braces, like this: {}.
Accessing Values in Dictionary:
• To access dictionary elements, you use the familiar square brackets along with the key to obtain its
value:
• Example:
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};
print "dict['Name']: ", dict['Name'];
print "dict['Age']: ", dict['Age'];
• This will produce following result:
dict['Name']: Zara
dict['Age']: 7
• If we attempt to access a data item with a key which is not part of the dictionary, we get an error as
follows:
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};
print "dict['Alice']: ", dict['Alice'];
• This will produce following result:
dict['Zara']:
Traceback (most recent call last): File "test.py", line 4, in <module> print
"dict['Alice']: ", dict['Alice']; KeyError: 'Alice'
Updating Dictionary:
• You can update a dictionary by adding a new entry or item (i.e., a key-value pair), modifying an existing entry, or
deleting an existing entry as shown below:
• Example:
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};
dict['Age'] = 8; # update existing entry
dict['School'] = "DPS School"; # Add new entry
print "dict['Age']: ", dict['Age'];
print "dict['School']: ", dict['School'];
• This will produce following result:
dict['Age']: 8
dict['School']: DPS School
Delete Dictionary Elements:
• You can either remove individual dictionary elements or clear the entire contents of a dictionary. You can also
delete entire dictionary in a single operation.
• To explicitly remove an entire dictionary, just use the del statement:
• Example:
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};
del dict['Name']; # remove entry with key 'Name' d
ict.clear(); # remove all entries in dict
del dict ; # delete entire dictionary
print "dict['Age']: ", dict['Age'];
print "dict['School']: ", dict['School'];
• This will produce following result. Note an exception raised, this is because after del dict dictionary does not
exist any more:
dict['Age']:
Traceback (most recent call last): File "test.py", line 8, in <module> print "dict['Age']: ",
dict['Age'];
TypeError: 'type' object is unsubscriptable
• Note: del() method is discussed in subsequent section.
Properties of Dictionary Keys:
• Dictionary values have no restrictions. They can be any arbitrary Python object, either standard objects or user-
defined objects. However, same is not true for the keys.
• There are two important points to remember about dictionary keys:
• (a) More than one entry per key not allowed. Which means no duplicate key is allowed. When duplicate keys
encountered during assignment, the last assignment wins.
• Example:
dict = {'Name': 'Zara', 'Age': 7, 'Name': 'Manni'};
print "dict['Name']: ", dict['Name'];
• This will produce following result:
dict['Name']: Manni
• (b) Keys must be immutable. Which means you can use strings, numbers, or tuples as dictionary keys
but something like ['key'] is not allowed.
• Example:
dict = {['Name']: 'Zara', 'Age': 7};
print "dict['Name']: ", dict['Name'];
• This will produce following result. Note an exception raised:
Traceback (most recent call last):
File "test.py", line 3, in <module> dict = {['Name']: 'Zara', 'Age': 7};
TypeError: list objects are unhashable
Built-in Dictionary Functions & Methods:
SN Function with Description
1 cmp(dict1, dict2)
Compares elements of both dict.
2 len(dict)
Gives the total length of the dictionary. This would be equal to the number of items in the
dictionary.
3 str(dict)
Produces a printable string representation of a dictionary
4 type(variable)
Returns the type of the passed variable. If passed variable is dictionary then it would return a
dictionary type.
SN Methods with Description
1 dict.clear()
Removes all elements of dictionary dict
2 dict.copy()
Returns a shallow copy of dictionary dict
2 dict.fromkeys()
Create a new dictionary with keys from seq and values set to value.
3 dict.get(key, default=None)
For key key, returns value or default if key not in dictionary
4 dict.has_key(key)
Returns true if key in dictionary dict, false otherwise
5 dict.items()
Returns a list of dict's (key, value) tuple pairs
6 dict.keys()
Returns list of dictionary dict's keys
7 dict.setdefault(key, default=None)
Similar to get(), but will set dict[key]=default if key is not already in dict
8 dict.update(dict2)
Adds dictionary dict2's key-values pairs to dict
9 dict.values()
Returns list of dictionary dict2's values
Python - Modules
• A module allows you to logically organize your Python code. Grouping related code into a module makes the
code easier to understand and use.
• A module is a Python object with arbitrarily named attributes that you can bind and reference.
• Simply, a module is a file consisting of Python code. A module can define functions, classes, and variables. A
module can also include runnable code.
• Example:
• The Python code for a module named aname normally resides in a file named aname.py. Here's an example of a
simple module, hello.py
def print_func( par ):
print "Hello : ", par
return
The import Statement:
• You can use any Python source file as a module by executing an import statement in some other Python source
file. import has the following syntax:
import module1[, module2[,... moduleN]
• When the interpreter encounters an import statement, it imports the module if the module is present in the
search path. A search path is a list of directories that the interpreter searches before importing a module.
• Example:
import hello
hello.print_func("Zara")
This would produce following result:
Hello : Zara
• A module is loaded only once, regardless of the number of times it is imported. This prevents the module
execution from happening over and over again if multiple imports occur.
The from...import * Statement:
It is also possible to import all names from a module into the current namespace by using the following import
statement:
from modname import *
• This provides an easy way to import all the items from a module into the current namespace; however, this
statement should be used sparingly.
Locating Modules:
When you import a module, the Python interpreter searches for the module in the following sequences:
• The current directory.
• If the module isn't found, Python then searches each directory in the shell variable PYTHONPATH.
• If all else fails, Python checks the default path. On UNIX, this default path is normally /usr/local/lib/python/.
The module search path is stored in the system module sys as the sys.path variable. The sys.path variable contains
the current directory, PYTHONPATH, and the installation-dependent default.
The PYTHONPATH Variable:
• The PYTHONPATH is an environment variable, consisting of a list of directories. The syntax of
PYTHONPATH is the same as that of the shell variable PATH.
• Here is a typical PYTHONPATH from a Windows system:
set PYTHONPATH=c:\python20\lib;
• And here is a typical PYTHONPATH from a UNIX system:
set PYTHONPATH=/usr/local/lib/python
Namespaces and Scoping:
• Variables are names (identifiers) that map to objects. A namespace is a dictionary of variable names (keys) and their
corresponding objects (values).
• A Python statement can access variables in a local namespace and in the global namespace. If a local and a global variable have
the same name, the local variable shadows the global variable.
• Each function has its own local namespace. Class methods follow the same scoping rule as ordinary functions.
• Python makes educated guesses on whether variables are local or global. It assumes that any variable assigned a value in a
function is local.
• Therefore, in order to assign a value to a global variable within a function, you must first use the global statement.
• The statement global VarName tells Python that VarName is a global variable. Python stops searching the local namespace for
the variable.
• For example, we define a variable Money in the global namespace. Within the function Money, we assign Money a value .
therefor Python assumes Money is a local variable. However, we access the value of the local variable Money before setting it,
so an UnboundLocalError is the result. Uncommenting the global statement fixes the problem.
Example:
Money = 2000
def AddMoney():
Money = Money + 1
print Money
AddMoney()
print Money
The dir( ) Function:
• The dir() built-in function returns a sorted list of strings containing the names defined by a module.
• The list contains the names of all the modules, variables, and functions that are defined in a module.
• Example:
import math
content = dir(math)
print content;
• This would produce following result:
['__doc__', '__name__', '__package__', 'acos', 'acosh', 'asin', 'asinh',
'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees',
'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod',
'frexp', 'fsum', 'gamma', 'hypot', 'isinf', 'isnan', 'ldexp', 'lgamma',
'log', 'log10', 'log1p', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh',
'sqrt', 'tan', 'tanh', 'trunc']
The globals() and locals() Functions:
• The globals() and locals() functions can be used to return the names in the global and local
namespaces depending on the location from where they are called.
• If locals() is called from within a function, it will return all the names that can be accessed locally
from that function.
• If globals() is called from within a function, it will return all the names that can be accessed
globally from that function.
• The return type of both these functions is dictionary. Therefore, names can be extracted using the
keys() function.
The reload() Function:
• When the module is imported into a script, the code in the top-level portion of a module is executed
only once.
• Therefore, if you want to reexecute the top-level code in a module, you can use the reload() function.
The reload() function imports a previously imported module again.
• Syntax:
The syntax of the reload() function is this:
reload(module_name)
Here module_name is the name of the module you want to reload and not the string containing the
module name. For example to re-load hello module, do the following:
reload(hello)
Packages in Python:
Example:
Consider a file Pots.py available in Phone directory. This file has following line of source code:
def Pots():
print "I'm Pots Phone"
Similar way we have another two files having different functions with the same name as above:
Phone/Isdn.py file having function Isdn()
Phone/G3.py file having function G3()
Now create one more file __init__.py in Phone directory :
Phone/__init__.py
To make all of your functions available when you've imported Phone, you need to put explicit import
statements in __init__.py as follows:
from Pots import Pots
from Isdn import Isdn
from G3 import G3
Note: Application file (e.g. package.py) should be saved in the parent directory of Phone sub-directory.