u2_Python.docx
u2_Python.docx
Lists, Tuples, Sets, Strings, Dictionary, Modules: Module Loading and Execution – Packages – Making Your
OwnModule – The Python Standard Libraries.
In Python, the list is a collection of items of different data types. It is an ordered sequence of
items. A list object contains one or more items, not necessarily of the same type, which are
separated by comma and enclosed in square brackets [].
Syntax:
list = [value1, value2, value3,...valueN]
# list of floats
num_list = [11.22, 9.9, 78.34, 12.0]
# an empty list
nodata_list = []
>>> superstore[9]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
Example:
# a list of numbers
numbers = [11, 22, 33, 100, 200, 300]
print(numbers[0])
print(numbers[5])
print(numbers[1])
Output
11
300
22
Slicing of lists is allowed in Python wherein a part of the list can be extracted by specifying
index range along with the colon (:) operator which itself is a list.
The syntax for list slicing is,
print(n_list[1:3])
Output:
# list items from beginning to 3rd
print(n_list[:3]) [2, 3.4]
# list items from 4th to end of list [1, 2, 3,4]
print(n_list[3:])
[4, 5, 6, 7]
# Whole list
print(n_list[:]) [1, 2, 3, 4, 5, 6, 7]
List Operations
Delete elements
# list of numbers
n_list = [1, 2, 3, 4, 5, 6] Output
del n_list[1] [1, 3, 4, 5, 6]
print(n_list)
[1, 2, 6]
del n_list[2:4]
print(n_list) []
# Deleting the whole list
del n_list
# list of chars
ch_list = ['A', 'F', 'B', 'Z', 'O', 'L']
# Deleting the element with value 'B' Output:
ch_list.remove('B')
print(ch_list) ['A', 'F', 'Z', 'O', 'L']
4. >>> type(forest)
<class 'list'>
5. >>> forest
['Lion', 'Tiger', 'Zebra']
8. >>> forest
['Fox', 'Tiger', 'Zebra']
For example,
1. >>> lakes = ['superior', 'erie', 'huron', 'ontario', 'powell']
2. >>> len(lakes)
5
3. >>> numbers = [1, 2, 3, 4, 5]
4. >>> sum(numbers)
15
5. >>> max(numbers)
5
6. >>> min(numbers)
1
Syntax
any(iterable)
The iterable object can be a list, tuple or dictionary.
Example 1
Using any() on Python Lists
# True since 1,3 and 4 (at least one) is true
l = [1, 3, 4, 0]
print(any(l))
Python all()
The all() method returns True when all elements in the given iterable are true. If not, it returns
False.
True
# all values false
False
l = [0, False]
False
print(all(l))
False
True
# one false value
l = [1, 3, 4, 0]
print(all(l))
# empty iterable
l=[]
print(all(l))
Tuple vs List
1. The elements of a list are mutable whereas the elements of a tuple are immutable.
2. When we do not want to change the data the tuple is a preferred data type whereas when we
need to change the data in future, list is a wise option.
3. Iterating over the elements of a tuple is faster compared to iterating over a list.
4. Elements of a tuple are enclosed in parenthesis( ) whereas the elements of list are enclosed in
square bracket [].
Empty tuple:
my_data = ( )
# tuple of strings
my_data = ("hi", "hello", "bye")
1. TypeError: If you do not use integer indexes in the tuple. For example my_data[2.0] will raise
this error. The index must always be an integer.
2. IndexError: Index out of range. This error occurs when we mention the index which is not in
the range. For example, if a tuple has 5 elements and we try to access the 7th element then this
error would occur.
print(my_data[-3])
Output
8.9
2
# prints 'v'
print(my_data[1][3])
# prints 22
print(my_data[2][1])
Output:
v
22
Tuple Operations
Changing the elements of a tuple
We cannot change the elements of a tuple because elements of tuple are immutable. However we
can change the elements of nested items that are mutable. For example, in the following code, we
are changing the element of the list which is present inside the tuple. List items are mutable
that’s why it is allowed.
List
From 5th element to last Output : (55, 66, 77, 88, 99)
print(my_data[4:])
Output:
Membership Test in Tuples (11, 22, 33, 44, 55, 66, 77, 88, 99)
True
in: Checks whether an element exists in the specified tuple.
False
not in: Checks whether an element does not exist in the specified
False
tuple.
my_data = (11, 22, 33, 44, 55, 66, 77, 88, 99) True
print(my_data)
# true
print(22 in my_data)
# false
print(2 in my_data)
# false
print(88 not in my_data)
# true
print(101 not in my_data)
Banana
However, a dictionary with a list as a key is not valid, as the list is mutable (changeable):
>>>dict={["Mango","Banana"]:"Fruit", ["Blue", "Red"]: "Colour"}
TypeError: unhashable type: 'list'
But, a list can be used as a value.
>>>dict={"Fruit":["Mango","Banana"], "Colour":["Blue", "Red"]}
The same key cannot appear more than once in a collection. If the key appears more than once,
only the last will be retained. The value can be of any data type. One value can be assigned to
more than one key.
>>>staff
Output
{"Krishna":"Officer", "Steve":"Manager", "Anil":"Clerk", "John":"Manager"}
However, when key 'John' is assigned two different values, only the latest is retained .
(overwriting the previous value).
Accessing a Dictionary
Dictionary is not an ordered collection, so a value cannot be accessed using an index in square
brackets. A value in a dictionary can be fetched using the associated key, using
the get() method. Specify the key in the get() method to retrieve its value.
>>>points={"p1":(10,10), "p2":(20,20)}
>>>points.get("p2")
Output: (20,20)
>>>numbers={1:"one", 2:"Two", 3:"three",4:"four"}
>>>numbers.get(2)
Output : 'Two’
Output
Key = 'USA', Value = 'Washington'
Key = 'France', Value = 'Paris'
Key = 'Japan', Value = 'Tokyo'
Key = 'India', Value = 'New Delhi'
Updating a Dictionary
As mentioned earlier, the key cannot appear more than once. Use the same key and assign a new
value to it to update the dictionary object.
Example : 1
>>> captains={"England":"Root", "Australia":"Smith", "India":"Dhoni"}
>>> captains['India']='Virat'
>>> captains['Australia']='Paine'
>>> captains
Output
{'England': 'Root', 'Australia': 'Paine', 'India': 'Virat'}
Example 2:
>>> capital={"Andhrapradesh":"Amaravathy", "Maharashtra ":"Mumbai",
"Tamilnadu":"Madras"}
>>> capital[‘Tamilnadu’]=’Chennai’
Output
>>> capital {‘Andhrapradesh ‘: ’Hyderabad’, ‘Maharashtra ‘: ‘Mumbai’,
‘Tamilnadu’:’chennai’}
>>>capital[‘Karnataka’]=’Bengalure’
Use a new key and assign a value to it. The dictionary will show an additional key-value pair in
it.
>>> capital {‘Andhrapradesh ‘: ’Hyderabad’, ‘Maharashtra ‘: ‘Mumbai’, ‘Tamilnadu’:’chennai’,
‘Karnataka’ : ‘Bengalure'}
Deleting Values from a Dictionary
Use the del keyword to delete a pair from a dictionary or the dictionary object itself. To delete a
pair, use its key as parameter. To delete a dictionary object, use its name.
>>> capital= {‘Andhrapradesh ‘: ’Hyderabad’, ‘Maharashtra ‘: ‘Mumbai’,
‘Tamilnadu’:’chennai’, ‘Karnataka’ : ‘Bengalure'}
Del[capital]=’Karnataka’
Oultput
>>> capital {‘Andhrapradesh ‘: ’Hyderabad’, ‘Maharashtra ‘: ‘Mumbai’,
‘Tamilnadu’:’chennai’}
View Keys and Values
The keys() and values() methods of Python dictionary class return a view object consisting of
keys and values respectively, used in the dictionary.
>>> d1 = {'name': 'Steve', 'age': 21, 'marks': 60, 'course': 'Computer Engg'}
>>>d1.keys()
>>> keys
dict_keys(['name', 'age', 'marks', 'course'])
>>>d1.update({"college":"ABC college"})
>>> values
dict_values(['Steve', 21, 60, 'Computer Engg', ' ABC college'])
Multi-dimensional Dictionary
Let us assign roll numbers to these students and create a multi-dimensional dictionary with roll
number as key and the above dictionaries at their value.
>>> students={1:d1, 2:d2, 3:d3}
>>> students
{1: {'name': 'Steve', 'age': 25, 'marks': 60}, 2: {'name': 'Anil', 'age': 23, 'marks': 75}, 3: {'name':
'Asha', 'age': 20, 'marks': 70}}<
The students object is a two-dimensional dictionary. Here d1, d2 and d3 are assigned as values to
keys 1,2, and 3, respectively. students [1] returns d1.
>>> students[1]
{'name': 'Steve', 'age': 25, 'marks': 60}
max() - If all keys in the dictionary are numbers, the heighest number will be returned. If all
keys in the dictionary are strings, the one that comes last in alphabetical order will be returned.
Based on Ascii value.
>>> lang={'J':'Java', 'A': 'ActionScript', 'P':'Python'}
>>> max(lang)
Output 'P'
min() - If all keys in the dictionary are numbers, the lowest number will be returned. If all keys
in the dictionary are strings, the one that comes first in alphabetical order will be returned.
>>> lang={'J':'Java', 'A': 'ActionScript', 'P':'Python'}
>>> min(lang)
'A'
>>> num={5:"five", 100:"hundred",3:"three"}
>>> min(num)
Output 3
pop() - Returns the value associated with the key and the corresponding key-value pair is
removed.
>>> capital= {‘Andhrapradesh ‘: ’Amaravathy’, ‘Maharashtra ‘: ‘Mumbai’,
‘Tamilnadu’:’chennai’, ‘Karnataka’ : ‘Bengalure'}
>>>capital.pop(‘Maharashtra’)
‘Mumbai’
>>>capital
{‘Andhrapradesh ‘: ’Hyderabad’, ‘Tamilnadu’:’chennai’, ‘Karnataka’ : ‘Bengalure'}
Items - Returns a list of tuples, each tuple containing the key and value of each pair.
>>> capital= {‘Andhrapradesh ‘: ’Hyderabad’, ‘Maharashtra ‘: ‘Mumbai’,
‘Tamilnadu’:’chennai’, ‘Karnataka’ : ‘Bengalure'}
>>> capital.items( )
dict_items(((‘Andhrapradesh ‘: ’Hyderabad’, ‘Maharashtra ‘: ‘Mumbai’, ‘Tamilnadu’:’chennai’,
‘Karnataka’ : ‘Bengalure')])
Keys
Returns a list object comprising of the keys in the dictionary.
>>>capital.keys
dict_keys([‘Andhrapradesh’, ‘Maharashtra ‘, ‘Tamilnadu’, ‘Karnataka’ ])
values():
Returns a list object comprising of the values in the dictionary.
>>>capital.values
dict_values([‘Hyderabad’, ‘Mumbai’, ‘chennai’, ‘Bengalure'])
Sets
Sets are used to store multiple items in a single variable. Set is a built-in data types in Python
used to store collections of data. Example: birds = {"parrot", "peacok", "dove"}
A set is a collection which is both unordered and unindexed. Sets are written with curly brackets.
Example
Create a Set:
thisset = {"apple", "banana", "cherry"}
print(thisset)
# Note: the set list is unordered, meaning: the items will appear in a random order.
List allows duplicates while Set doesn't allow duplicate elements, it omits to display.
Set items are unordered, unchangeable, and do not allow duplicate values.
Unordered
Unordered means that the items in a set do not have a defined order.
Set items can appear in a different order every time you use them, and cannot be referred to by
index or key.
Unchangeable
Sets are unchangeable, meaning that we cannot change the items after the set has been created.
Once a set is created, you cannot change its items, but you can add new items.
print(thisset)
o/p {'banana', 'cherry', 'apple'}
Example
thisset = {"apple", "banana", "cherry"}
print(len(thisset))
o/p 3
Set Items - Data Types
Type( )
myset = {"apple", "banana", "cherry"}
print(type(myset)
o/p <class 'set'>
PYTHON STRINGS
String is a sequence of characters which are surrounded by either single quotation marks, or
double quotation marks or Triple quotation marks.
'hello' is the same as "hello". A Python string is an immutable sequence of characters; these
characters can be alphabets, numbers (from 0 to 9), white-spaces, etc.
Python does not have a character data type, a single character is simply a string with a length of
1. Square brackets can be used to access elements of the string.
To create a String in Python
1. We can use ‘ (single quotes), see the string str in the following code.
2. We can use ” (double quotes), see the string str2 in the source code below.
3. Triple double quotes “””” and triple single quotes ”’ are used for creating multi-line strings
in Python.
Output
# lets see the ways to create strings in Python
beginnersbook
str = 'beginnersbook'
Chaitanya
print(str)
Welcome to
Beginnersbook.com
str2 = "Chaitanya"
This is a tech
print(str2)
Blog
# multi-line string
str3 = """Welcome to
Beginnersbook.com"""
print(str3)
A string is nothing but an array of characters so we can use the indexes to access the characters
of a it. Just like arrays, the indexes start from 0 to the length-1.
You will get IndexError if you try to access the character which is not in the range. For
example,
if a string is of length 6 and you try to access the 8th char of it then you will get this error.
You will get TypeError if you do not use integers as indexes.
str = "Kevin"
Example
Get the character at position 1 (remember that the first character has the position 0):
a = "Hello, World!"
print(a[1])
Output
C:\Users\My Name>python demo_string1.py
e
STRIP
The strip() method removes any whitespace from the beginning or the end:
a=" Hello, World! "
print(a.strip( ))
Output
"Hello, World!"
Length()
The len() method returns the length of a string:
a = "Hello, World!"
print(len(a))
Output : 13
Lower
The lower() method returns the string in lower case:
a = "Hello, World!"
print(a.lower())
Upper
The upper() method returns the string in upper case:
a = "Hello, World!"
print(a.upper())
Replace Characters
The replace() method replaces a string with another string:
a = "Hello, World!"
print(a.replace("H", "J"))
O/P Jello, World!
SPLIT
The split() method splits the string into substrings if it finds instances of the separator:
a = "Hello, World!"
print(a.split(","))
O/P ['Hello', 'World!']
Slicing
str = "Beginnersbook"
Slice a string to get a substring out of it.
# displaying whole string
print("The original string is: ", str)
O/P The original string is: Beginnersbook
O/p OneTwoThree
Repetition of string – Replication operator
str = "ABC"
str2 = "aBC"
str3 = "XYZ"
str4 = "XYz"
String center()
The center() method returns a string which is padded with the specified character.
The syntax of center() method is: string.center(width[, fillchar])
center() Parameters
The center() method takes two arguments:
width - length of the string with padded characters
fillchar (optional) - padding character
The fillchar argument is optional. If it's not provided, space is taken as default argument.
center() Method With * fillchar
string = "Python is awesome"
String capitalize()
In Python, the capitalize() method converts first character of a string to uppercase letter and
lowercases all other characters, if any.
The syntax of capitalize() is: string.capitalize()
string = "python is AWesome."
capitalized_string = string.capitalize()
Output
Capitalized String: Python is awesome.
String count()
The string count() method returns the number of occurrences of a substring in the given
string.
Output
The count is: 2
It also takes optional parameters start and end to specify the starting and ending positions in the
string respectively.
Python String find()
The find() method returns the index of first occurrence of the substring (if found). If not found, it
returns -1.
The syntax of find() method is: str.find(sub[, start[, end]] )
find() Parameters
The find() method takes maximum of three parameters:
sub - It's the substring to be searched in the str string.
start and end (optional) - substring is searched within str[start:end]
string.isupper()
Output: True
# lowercase string
string = "THIS IS not GOOD!"
print(string.isupper());
Output : False
Python allows for command line input. That means we are able to ask the user for input.
The following example asks for the user's name, then, by using the input() method, the
program prints the name to the screen:
demo_string_input.py
print("Enter your name:")s
x = input()
print("Hello, " + x)
Save this file as demo_string_input.py, and load it through the command line:
C:\Users\Your Name>python demo_string_input.py
Escape Sequences
The escape character is used to invoke an alternative implementation of the subsequent character
in a sequence. In Python backslash \ is used as an escape character. Here is a list of escape
sequences and their purpose.
String Operators
Obviously, arithmetic operators don't operate on strings. However, there are special operators for
string processing.
String Formatting
def SayHello(name):
print("Hello " + name)
return
functions.py
def sum(x,y):
return x+y
def average(x,y):
return (x+y)/2
def power(x,y):
return x**y
We have created our package called mypackage. The following is a folder structure:
Now, to test our package, invoke the Python prompt from the MyApp folder.
D:\MyApp>python
Import the functions module from the mypackage package and call its power() function.
>>> from mypackage import functions
>>> functions.power(3,2)
9
__init__.py
The package folder contains a special file called __init__.py, which stores the package's content. It
serves two purposes:
An empty __init__.py file makes all functions from above modules available when this package
is imported. Note that __init__.py is essential for the folder to be recognized by Python as a
package. You can optionally define functions from individual modules to be made available.
The __init__.py file is normally kept empty. However, it can also be used to choose specific
functions from modules in the package folder and make them available for import. Modify
__init__.py as below:
__init__.py
from .functions import average, power
from .greet import SayHello
The specified functions can now be imported in the interpreter session or another executable
script.
test.py
from mypackage import power, average, SayHello
SayHello()
x=power(3,2)
print("power(3,2) : ", x)
Note that functions power() and SayHello() are imported from the package and not from their
respective modules, as done earlier. The output of above script is:
D:\MyApp>python test.py
Hello world
power(3,2) : 9
Install a Package Globally
Once a package is created, it can be installed for system wide use by running the setup script.
The script calls setup() function from setuptools module.
Let's install mypackage for system-wide use by running a setup script.
Save the following code as setup.py in the parent folder 'MyApp'. The script calls
the setup() function from the setuptools module. The setup() function takes various
arguments such as name, version, author, list of dependencies etc. The zip_safe argument defines
whether the package is installed in compressed mode or regular mode.
Example: setup.py
from setuptools import setup
setup(name='mypackage',
version='0.1',
description='Testing installation of Package',
url='#',
author='malhar',
author_email='mlathkar@gmail.com',
license='MIT',
packages=['mypackage'],
zip_safe=False)
Now execute the following command to install mypack using the pip utility. Ensure that the
command prompt is in the parent folder, in this case D:\MyApp.
D:\MyApp>pip install .
Processing d:\MyApp
Installing collected packages: mypack
Running setup.py install for mypack ... done
Successfully installed mypackage-0.1
Now mypackage is available for system-wide use and can be imported in any script or
interpreter.
D:\>python
>>> import mypackage
>>>mypackage.average(10,20)
15.0
>>>mypackage.power(10,2)
100
You may also want to publish the package for public use. PyPI (stands for Python Package
Index) is a repository of Python packages and is hosted at www.pypi.org
4.22 Module
A file containing a set of functions you want to include in your application.
Create a Module
To create a module just save the code you want in a file with the file extension .py:
Example
mymodule.py
def greeting(name):
print("Hello, " + name)
Use a Module
Now we can use the module we just created, by using the import statement:
Example
Import the module named mymodule, and call the greeting function:
demo_module1.py:
import mymodule
mymodule.greeting("Jonathan")
O/p
C:\Users\My Name>python demo_module1.py
Hello, Jonathan
Variables in Module
The module can contain functions but also variables of all types (arrays, dictionaries, objects
etc):
mymodule.py
person1 = {
"name": "John",
"age": 36,
"country": "Norway"
}
Import the module named mymodule, and access the person1 dictionary:
import mymodule
a = mymodule.person1["age"]
print(a)
Output
C:\Users\My Name>python demo_module2.py
36
Naming a Module
You can name the module file , but it must have the file extension .py
Re-naming a Module
You can create an alias when you import a module, by using the as keyword:
Create an alias for mymodule called mx:
import mymodule as mx
a = mx.person1["age"]
print(a)
Output
C:\Users\My Name>python demo_module3.py
36
Built-in Modules
There are several built-in modules in Python, which you can import whenever you like.
Import and use the platform module:
import platform
x = platform.system()
print(x)
There is a built-in function to list all the function names (or variable names) in a module. The
dir() function can be used on all modules, also the ones you create yourself.
The dir() function:
List all the defined names belonging to the platform module:
import platform
x = dir(platform)
print(x)
o/p
You can choose to import only parts from a module, by using the from keyword.
The module named mymodule has one function and one dictionary:
def greeting(name):
print("Hello, " + name)
person1 = {
"name": "John",
"age": 36,
"country": "Norway"
}
print (person1["age"])
o/p C:\Users\My Name>python demo_module6.py
36
Protected members of a class are accessible from within the class and are also available to its
sub-classes. No other environment is permitted access to it. This enables specific resources of the
parent class to be inherited by the child class.
All members in a Python class are public by default. Any member can be accessed from outside
the class environment.
You can access employee class's attributes and also modify their values, as shown below.
>>> e1=Employee("Kiran",10000)
>>> e1.salary
10000
>>> e1.salary=20000
>>> e1.salary
20000
class employee:
def __init__(self, name, sal):
self._name=name # protected attribute
self._salary=sal # protected attribute
class employee:
def __init__(self, name, sal):
self.__name=name # private attribute
self.__salary=sal # private attribute
>>> e1=employee("Bill",10000)
>>> e1.__salary
AttributeError: 'employee' object has no attribute '__salary'
Python performs name mangling of private variables. Every member with double underscore will
be changed to _object._class__variable. If so required, it can still be accessed from outside the
class, but the practice should be refrained.
>>> e1=Employee("Bill",10000)
>>> e1._Employee__salary
10000
>>> e1._Employee__salary=20000
>>> e1._Employee__salary
20000