Python Unit 3
Python Unit 3
Unit 3
Janhavi Vadke
Topics
• Lists:
• Tuples and Dictionaries:
• Files:
• Exceptions:
Lists
• The list is a most versatile datatype available in Python
which can be written as a list of comma-separated
values (items) between square brackets.
• Important thing about a list is that items in a list need
not be of the same type.
• e.g :
• list1 = ['physics', 'chemistry', 1997, 2000]
• list2 = [1, 2, 3, 4, 5 ]
• list3 = ["a", "b", "c", "d"]
• list indices start at 0, and lists can be sliced,
concatenated and so on.
Accessing value
• To access values in lists, use the square
brackets for slicing along with the index or
indices to obtain value available at that
index
• Index starts with 0.
• Last element has index -1.
• print(List1[0])
• print(List1[-1])
• list1 = ['physics', 'chemistry', 1997, 2000]
• list2 = [1, 2, 3, 4, 5, 6, 7 ]
• print ("list1[0]: ", list1[0])
• print ("list2[1:5]: ", list2[1:5])
• o/p
• list1[0]: physics
• list2[1:5]: [2, 3, 4, 5]
Lists are Mutable
• List are mutable, meaning, their elements can be
changed unlike string or tuple
• We can update single or multiple elements of lists by
giving the slice on the left-hand side of the assignment
operator.
• list = ['physics', 'chemistry', 1997, 2000]
print ("Value available at index 2 : “)
print (list[2])
list[2] = 2001
print ("New value available at index 2 : " )
print (list[2])
• We can add one item to a list using append() method or
add several items using extend() method.
• odd = [1, 3, 5]
1)odd.append(7)
• print(odd) # Output: [1, 3, 5, 7]
2)odd.extend([9, 11, 13])
• print(odd) # Output: [1, 3, 5, 7, 9, 11, 13]
• Furthermore, we can insert one item at a desired location
by using the method insert()
• odd = [1, 9]
3)odd.insert(1,3)
• print(odd) # Output: [1, 3, 9]
Traversing a List
• Using a for loop we can iterate though each
item in a list.
• for fruit in ['apple','banana','mango']:
print("I like",fruit)
Delete List Elements
• To remove a list element, you can use either
the del statement if you know exactly which
element(s) you are deleting
• list1 = ['physics', 'chemistry', 1997, 2000]
• print (list1)
• del list1[2]
• print "After deleting value at index 2 : "
• print (list1)
• We can use remove() method to remove the
given item if exact element is not known.
• my_list = ['p','r','o','b','l','e','m']
• my_list.remove('p')
• print(my_list) # Output: ['r', 'o', 'b', 'l', 'e', 'm']
• my_list.clear()
• print(my_list) # Output: []
Built in List Operators
• Lists respond to the + and * operators much like strings; they mean
concatenation and repetition here too, except that the result is a
new list, not a string.
• >>> a = [1, 2, 3]
• >>> b = [4, 5, 6]
• >>> c = a + b
• >>> print c
• [1, 2, 3, 4, 5, 6]
• The * operator repeats a list a given number of times:
• >>> [0] * 4
• [0, 0, 0, 0]
• >>> [1, 2, 3] * 3
• [1, 2, 3, 1, 2, 3, 1, 2, 3]
List Membership Test
• We can test if an item exists in a list or not, using
the keyword in.
• my_list = ['p','r','o','b','l','e','m']
• print('p' in my_list)
• # Output: True
• print('a' in my_list)
• # Output: False
• print('c' not in my_list)
• # Output: True
Built in List Methods
• append() - Add an element to the end of the list
• extend() - Add all elements of a list to the another list
• insert() - Insert an item at the defined index
• remove() - Removes an item from the list
• pop() - Removes and returns an element at the given index
• clear() - Removes all items from the list
• index() - Returns the index of the first matched item
• count() - Returns the number of times the value appears int
the list
• sort() - Sort items in a list in ascending order
• reverse() - Reverse the order of items in the list
• copy() - Returns a shallow copy of the list
Built-in Functions
• Built-in functions like all(), any(), enumerate(),
len(), max(), min(), list(), sorted() etc. are
commonly used with list to perform different
tasks.
Function Description
9) dict.update(dict2)
• Adds dictionary dict2's key-values pairs to dict.
10) dict.values()
• Returns list of dictionary dict's values.
Python len() Returns Length of an Object
StopIteration Raised when the next() method of an iterator does not point to any object.
StandardError Base class for all built-in exceptions except StopIteration and SystemExit.
ArithmeticError Base class for all errors that occur for numeric calculation.
OverflowError Raised when a calculation exceeds maximum limit for a numeric type.
ZeroDivisionError Raised when division or modulo by zero takes place for all numeric types.
EOFError Raised when there is no input from either the raw_input() or input() function and the end of file is reached.
KeyboardInterrupt Raised when the user interrupts program execution, usually by pressing Ctrl+c.
NameError Raised when an identifier is not found in the local or global namespace.
UnboundLocalError Raised when trying to access a local variable in a function or method but no value has been assigned to it.
EnvironmentError Base class for all exceptions that occur outside the Python environment.
IOError Raised when an input/ output operation fails, such as the print statement or the open() function when trying to open a file that does not exist.
IOError Raised for operating system-related errors.
SystemError Raised when the interpreter finds an internal problem, but when this error is encountered the Python interpreter does not exit.
SystemExit Raised when Python interpreter is quit by using the sys.exit() function. If not handled in the code, causes the interpreter to exit.
TypeError Raised when an operation or function is attempted that is invalid for the specified data type.
ValueError Raised when the built-in function for a data type has the valid type of arguments, but the arguments have invalid values specified.
RuntimeError Raised when a generated error does not fall into any category.
NotImplementedError Raised when an abstract method that needs to be implemented in an inherited class is not actually implemented.
Handling an exception
• If you have some suspicious code that may
raise an exception, you can defend your
program by placing the suspicious code in a
try: block.
• After the try: block, include an except:
statement, followed by a block of code which
handles the problem as elegantly as possible.
• A single try statement can have multiple except
statements. This is useful when the try block
contains statements that may throw different
types of exceptions.
• You can also provide a generic except clause,
which handles any exception.
• After the except clause(s), you can include an
else-clause. The code in the else-block executes
if the code in the try: block does not raise an
exception.
• The else-block is a good place for code that
does not need the try: block's protection.
• 1) try-----except
try:
num=int(input("Enter the number"))
re=100/num
except(ZeroDivisionError):
print("please enter non zero value")
else:
print("Result is : ",re)
try:
fh = open("testfile", "w")
fh.write("This is my test file for exception handling!!")
except IOError:
print "Error: can\'t find file or read data"
else:
print "Written content in the file successfully"
fh.close()