0% found this document useful (0 votes)
8 views106 pages

Python Programming Unit - III, IV, V

Python Concepts

Uploaded by

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

Python Programming Unit - III, IV, V

Python Concepts

Uploaded by

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

PYTHON PROGRAMMING

UNIT III - Dictionaries

Dr. D.Kavitha
Creating Dictionary
 A dictionary is a collection of an unordered set of key:value pairs.
 Dictionaries are constructed using curly braces { }, wherein you include a list of key:value pairs
separated by commas.
 There is a colon (:) separating each of these key and value pairs.
 left of the colon -- keys
 right of the colon -- values.
 dictionaries are indexed by keys.
 Here a key along with its associated value is called a key:value pair.
 Dictionary keys are case sensitive. the keys are unique within a dictionary.
 Dictionary keys are immutable type and can be either a string or a number. Duplicate keys are
not allowed in the dictionary
Creating Dictionary
 dictionary_name = {key_1:value_1, key_2:value_2, key_3:value_3, ………,key_n:value_n}
 empty dictionary -- dictionary_name = { }
 pizza = {"pepperoni":3, "calzone":5, "margherita":4}
 mixed_dict = {"portable":"laptop", 9:11, 7:"julius"}
 The dict() Function: dict([**kwarg]) kwarg = value
 numbers = dict(one=1, two=2, three=3)
 Print(numbers)
 {'one': 1, 'two': 2, 'three': 3}
 The syntax for dict() function when iterables used is,
 dict(iterable[, **kwarg])
 1. >>> dict([('sape', 4139), ('guido', 4127), ('jack', 4098)])
 {'sape': 4139, 'jack': 4098, 'guido': 4127}
Accessing and Modifying key:value Pairs in Dictionaries
 The syntax for accessing the value for a key in the dictionary is, dictionary_name[key]
 The syntax for modifying the value of an existing key or for adding a new key:value pair to a
dictionary is, dictionary_name[key] = value
 the ordering of key:value pairs does not matter in dictionaries.
 Slicing is not allowed since they are not ordered like lists.
 Dictionaries remember the order in which the key:value pairs were inserted.
 check for the presence of a key in the dictionary using in and not in membership
 operators. It returns either a Boolean True or False value. For example,
 1. >>> clothes = {"rainy":"raincoats", "summer":"tees", "winter":"sweaters"}
 2. >>> "spring" in clothes
 False
 3. >>> "spring" not in clothes
 True
Populating Dictionaries with key:value Pairs

 1. start with an empty dictionary { }, then use the update() method to assign a value to the
key using assignment operator.
 1. >>> countries = {}
 2. >>> countries.update({"Asia":"India"})
 3. >>> countries.update({"Europe":"Germany"})
 5. >>> countries
 {'Asia': 'India', 'Europe': 'Germany'}
 6.>>>countries[„Africa‟] = “Zimbambwe”

 If the key does not exist, then the key:value pairs will be created automatically and added to
the dictionary
Removing an item from Dictionary
 To delete the key:value pair, use the del statement followed by the name of the dictionary along with
the key you want to delete.
 del dict_name[key]
 1. >>> animals = {"r":"raccoon", "c":"cougar", "m":"moose"}
 2. >>> del animals["c"]
 3. >>> animals {'r': 'raccoon', 'm': 'moose'}
 Pop -- Removes the removes the key from the dictionary and returns its value.
 Animal = animals.pop(„m‟)
 popitem() -- removes and returns an arbitrary (key, value) tuple pair from the dictionary
 Popped = animals.popitem()
 clear() -- to remove all items from a dictionary at once.
 Animals.clear()
Traversing of Dictionary/Accessing an item

 A for loop can be used to iterate over keys or values or key:value pairs in
dictionaries.
 If you iterate over a dictionary using a for loop, then, by default, you will
iterate over the keys.
 If you want to iterate over the values, use values() method and for iterating
over the key:value pairs, specify the dictionary‟s items() method explicitly.
 The dict_keys, dict_values, and dict_items data types returned by dictionary
methods can be used in for loops to iterate over the keys or values or key:value
pairs.
Traversing of Dictionary
 1. currency = {"India": "Rupee", "USA": "Dollar", "Russia": "Ruble", "Japan": "Yen", "Germany": "Euro"}
 2. def main():
 3. print("List of Countries")
 4. for key in currency.keys():
 5. print(key)
 6. print("List of Currencies in different Countries")
 7. for value in currency.values():
 8. print(value)
 9. for key, value in currency.items():
 10. print(f"'{key}' has a currency of type '{value}'")
 11. if __name__ == "__main__":
 12. main()
Built-In Functions Used on Dictionaries

 Built-In Functions Used on Dictionaries


 Built-in Functions Description
 len() -- The len() function returns the number of items (key:value pairs) in a dictionary.
 all() -- The all() function returns Boolean True value if all the keys in the dictionary are True else
returns False.
 any() -- The any() function returns Boolean True value if any of the key in the dictionary is True
else returns False.
 sorted() -- The sorted() function by default returns a list of items, which are sorted based on
dictionary keys.
Built-In Functions Used on Dictionaries
 1. >>> presidents = {"washington":1732, "jefferson":1751, "lincoln":1809,
 "roosevelt":1858, "eisenhower":1890}
 2. >>> len(presidents)
 5
 3. >>> all_dict_func = {0:True, 2:False}
 4. >>> all(all_dict_func)
 False
 5. >>> all_dict_func = {1:True, 2:False}
 6. >>> all(all_dict_func)
 True
 7. >>> any_dict_func = {1:True, 2:False}
 8. >>> any(any_dict_func)
 True
Built-In Functions Used on Dictionaries
 9. >>> sorted(presidents)
 ['eisenhower', 'jefferson', 'lincoln', 'roosevelt', 'washington']
 10. >>> sorted(presidents, reverse = True)
 ['washington', 'roosevelt', 'lincoln', 'jefferson', 'eisenhower']
 11. >>> sorted(presidents.values())
 [1732, 1751, 1809, 1858, 1890]
 12. >>> sorted(presidents.items())
 [('eisenhower', 1890), ('jefferson', 1751), ('lincoln', 1809), ('roosevelt', 1858),
 ('washington', 1732)]
Dictionary Methods
Tuples and Sets
 Tuple -- comprises an ordered, finite sequence of immutable, heterogeneous elements
that are of fixed sizes.
 tuple_name = (item_1, item_2, item_3, ………….., item_n)
 Empty tuple -- tuple_name = ()
 numbers = (1, 2, -5) letters = ("a", "b", "c")
 f1 = "ferrari", "redbull", "mercedes", "williams", "renault"
 You can store any item of type string, number, object, another variable, and even
another tuple itself
 mixed_tuple = (2, 'Hello', 'Python‟, numbers)
 nested_tuples = (letters, numbers)
 A tuple with one item is constructed by having a value followed by a comma.
 stuple = 'hello',
Tuples
 tuple() Function --- tuple([sequence])
 S1 = ‘kavitha’
 St = tuple(S1)
 St = (‘k’,’a’,’v’,’i’,’t’,’h’,’a’)
 L1 = [1,2,‟k‟,‟s‟]
 Lt = tuple(L1)
 Lt = (1,2,‟k‟,‟s‟)
 T = (1,2,3,4)
 T1 = ()
 T1 += (1,)
 Item = int(input(„enter tuple item:‟))
 T1 += (item,)
 Tuples are:
 Ordered - They maintain the order of elements.
 Immutable - They cannot be changed after creation.
 Allow duplicates - They can contain duplicate values.
Basic Tuple Operations
 + operator to concatenate tuples together
 * operator to repeat a sequence of tuple items.
 == tuples are compared
 in and not in membership operators - check for the presence of an item in a tuple
 <, <=, >, >=, == and != are used to compare tuples - <, <=, >, >=, == and != are used to compare
tuples
Accessing Tuple Items
 Indexing and Slicing in Tuples
 tuple_name[index]
 tuple_name[start:stop[:step]]
 Traversing Tuple Items
 fruits = ('apple','banana','orange')
 for fruit in fruits:
 print(fruit)
 For fruit in range(len(fruits)):
 print(fruit)
 Tuple Immutable
 Fruits[0] = „grape‟ --- not allowed
Built-In Functions Used on Tuples

 len() -- function returns the numbers of items in a tuple.


 sum() --- function returns the sum of numbers in the tuple.
 sorted() ---- function returns a sorted copy of the tuple as a list while leaving the original tuple
untouched. T1 = sorted(T)
 count() -- tuple_name.count(item) --- counts the number of times the item has occurred in the
tuple and returns it.
 index() -- tuple_name.index(item) --- searches for the given item from the start of the tuple and
returns its index. If the value appears more than once, you will get the index of the first one. If the
item is not present in the tuple, then ValueError is thrown by this method
Tuple Packing and Unpacking
 The statement t = 12345, 54321, 'hello!' is an example of tuple packing.
 1. >>> t = 12345, 54321, 'hello!'
 2. >>> t --- (12345, 54321, 'hello!')
 The values 12345, 54321 and 'hello!' are packed together into a tuple ➀–➁.
 Tuple Unpacking - The reverse operation of tuple packing is also possible.
 1. >>> x, y, z = t
 2. >>> x --- 12345
 3. >>> y --- 54321
 4. >>> z --- 'hello!'
 works for any sequence on the right-hand side.
 Tuple unpacking requires that there are as many variables on the left side of the equals sign as
there are items in the tuple
 2. a = int(input("Enter a value for first number "))
 3. b = int(input("Enter a value for second number "))
 4. b, a = a, b
 5. print("After Swapping")
 6. print(f"Value for first number {a}")
 7. print(f"Value for second number {b}")
Relation between Tuples and Lists
 Tuples are immutable, cannot be added, removed or replaced in a tuple.
 Can contain a heterogeneous sequence
 elements are accessed via unpacking or indexing.
 If an item within a tuple is mutable, then you can change it
 Lists are mutable.
 items are accessed via indexing.
 convert a tuple to a list by passing the tuple name to the list() function.
 L1 = [1,2,3]
 T1= (4,5,6,L1)
Relation between Tuples and Dictionaries
 Tuples can be used as key:value pairs to build dictionaries.
 For example,
 1. >>> fish_weight_kg = (("white_shark", 520), ("beluga", 1571), ("greenland_shark", 1400))
 2. >>> fish_weight_kg_dict = dict(fish_weight_kg)
 3. >>> fish_weight_kg_dict
 {'white_shark': 520, 'beluga': 1571, 'greenland_shark': 1400}
 The tuples can be converted to dictionaries by passing the tuple name to the dict() function.
 This is achieved by nesting tuples within tuples, wherein each nested tuple item should have two items
in it
zip() Function
 The zip() function makes a sequence that aggregates elements from each of the iterables (can
 be zero or more). The syntax for zip() function is,
 zip(*iterables)
 An iterable can be a list, string, or dictionary. It returns a sequence of tuples, where the i-th
 tuple contains the i-th element from each of the iterables. The aggregation of elements stops
 when the shortest input iterable is exhausted.
 1. >>> x = [1, 3, 5]
 2. >>> y = [2, 4, 6]
 3. >>> zipped = zip(x, y)
 4. >>> list(zipped)
 [(1, 2), (3, 4), (5, 6)]
 For o,e in zip(x,y):
 print(o,e)
Sets
 A set is an unordered collection with no duplicate items.
 A set is a collection of unique items.
 basket = {'apple', 'orange', 'pear', 'banana'}
 set() function can be used to create sets with a comma-separated list of items inside curly brackets
{ }.
 Note: to create an empty set you have to use set()
 not { } as this creates an empty dictionary.
 Sets support mathematical operations, such as union, intersection, difference, and symmetric
difference.
 Sets are mutable. Indexing is not possible in sets, since set items are unordered
 A = {'d', 'a', 'b', 'r', 'c'}
 B = {'m', 'l', 'c', 'z', 'a'}
 a – b -- {'b', 'r', 'd'}
 a | b -- {'l', 'm', 'z', 'd', 'a', 'b', 'r', 'c'}
 A & b -- {'a', 'c'}
 a ^ b -- {'l', 'd', 'm', 'b', 'r', 'z'}
 len(basket) -- 4
 sorted(basket) -- ['apple', 'banana', 'orange', 'pear']
 basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
 print(basket)
 {'pear', 'orange', 'banana', 'apple'}
Set Methods
Set Methods
 1. >>> european_flowers = {"sunflowers", "roses", "lavender", "tulips", "goldcrest"}

 2. >>> american_flowers = {"roses", "tulips", "lilies", "daisies"}

 3. >>> american_flowers.add("orchids")

 4. >>> american_flowers.difference(european_flowers) {'lilies', 'orchids', 'daisies'}

 5. >>> american_flowers.intersection(european_flowers) {'roses', 'tulips'}

 6. >>> american_flowers.isdisjoint(european_flowers) False

 7. >>> american_flowers.issuperset(european_flowers) False

 8. >>> american_flowers.issubset(european_flowers) False

 9. >>> american_flowers.symmetric_difference(european_flowers)

 {'lilies', 'orchids', 'daisies', 'goldcrest', 'sunflowers', 'lavender'}


Set Methods
 10. >>> american_flowers.union(european_flowers)

 {'lilies', 'tulips', 'orchids', 'sunflowers', 'lavender', 'roses', 'goldcrest', 'daisies'}


 11. >>> american_flowers.update(european_flowers)
 12. >>> american_flowers
 {'lilies', 'tulips', 'orchids', 'sunflowers', 'lavender', 'roses', 'goldcrest', 'daisies'}
 13. >>> american_flowers.discard("roses")
 14. >>> american_flowers
 {'lilies', 'tulips', 'orchids', 'daisies'}
 15. >>> european_flowers.pop() 'tulips'
 16. >>> american_flowers.clear()
 17. >>> american_flowers
 set()
 Traversing of Sets
 iterate through each item in a set using a for loop.
 Frozenset
 Frozenset -- immutable -- can be used as members in other sets and as dictionary keys
 The frozensets have the same functions as normal sets, except none of the functions that
change the contents (update, remove, pop,
 etc.) are available
Lists
 • Lists are a basic and useful data structure built into the Python language.

 • Built-in functions include len(), which returns the length of the list; max(), which returns the
maximum element in the list; min(), which returns the minimum element in the list and sum(),
which returns the sum of all the elements in the list.

 • An individual elements in the list can be accessed using the index operator [].

 • Lists are mutable sequences which can be used to add, delete, sort and even reverse list
elements.

 • The sort() method is used to sort items in the list.

 • The split() method can be used to split a string into a list.

 • Nested list means a list within another list.


Dictionary
 • A dictionary associates a set of keys with values.

 • The built-in function dict() returns a new dictionary initialized from an optional keyword
argument and a possibly empty set of keyword arguments.

 • The for loop is used to traverse all the keys in the dictionary.

 • The del dictionaryName[key] statement is used to delete an item for the given key.

 • Dictionary methods like keys(), values(), and items() are used to retrieve the values.

 • Methods like pop() and update() are used to manipulate the dictionary key:value pairs.
Sets and Tuples
 • Tuple is an immutable data structure comprising of items that are ordered and heterogeneous.

 • Tuples are formed using commas and not the parenthesis.

 • Indexing and slicing of items are supported in tuples.

 • Tuples support built-in functions such as len(), min(), and max().

 • The set stores a collection of unique values and are not placed in any particular order.

 • Add an item to the set using add() method and remove an item from the set using the remove() method.

 • The for loop is used to traverse the items in a set.

 • The issubset() or issuperset() method is used to test whether a set is a superset or a subset of another
set.

 • Sets also provide functions such as union(), intersection(), difference(), and symmetric_difference().
PYTHON PROGRAMMING
UNIT III - LISTS

Dr. D.Kavitha
LISTS
 List is a container that holds a number of items.
 Each element or value that is inside a list is called an item. All the items in a
list are assigned to a single variable.
 Lists can be simple or nested lists with varying types of values.
 Lists are constructed using square brackets [ ] wherein you can include a list of
items separated by commas.
 empty list - list_name = [ ] - item[]
 Lists - store = ["metro", "tesco", "walmart", "kmart", "carrefour"]
 list1 = [4, 4, 6, 7, 2, 9, 10, 15]
 list2 = ['dog', 87.23,‟apple‟, 65, [9, 1, 8, 1]]
LISTS

 Lists are:
 Ordered - They maintain the order of elements.
 Mutable - Items can be changed after creation.
 Allow duplicates - They can contain duplicate values.
Basic List Operations
 + sign – lists concatenation
 * sign - create a repeated sequence of list items
 1. >>> list_1 = [1, 3, 5, 7]
 2. >>> list_2 = [2, 4, 6, 8]
 3. >>> list_1 + list_2
 [1, 3, 5, 7, 2, 4, 6, 8]
 4. >>> list_1 * 3
 [1, 3, 5, 7, 1, 3, 5, 7, 1, 3, 5, 7]
 5. >>> list_1 == list_2
 False
 6. >>> 5 in list_1
 True
The list() Function

 The built-in list() function is used to create a list. The syntax for list()
function is, list([sequence])
 where the sequence can be a string, tuple or list itself. If the optional
sequence is not specified then an empty list is created.
 For example,
 1. >>> quote = "How you doing?"
 2. >>> string_to_list = list(quote)
 3. >>> string_to_list
 ['H', 'o', 'w', ' ', 'y', 'o', 'u', ' ', 'd', 'o', 'i', 'n', 'g', '?']
Indexing and Slicing in Lists
 The syntax for accessing an item in a list is, list_name[index]

 >>> superstore[3]
 'kmart„
 >>> superstore[-3]
 'walmart'
Modifying Items in Lists
 Lists can be modified.
 >>> fauna = ["pronghorn", "alligator", "bison"]
 >>> fauna[0] = "groundhog“ >>> fauna[-1] = "beaver"
 1. >>> zoo = ["Lion", "Tiger", "Zebra"]
 2. >>> forest = zoo
 Slicing of lists : list_name[start:stop:[step]]
 fruits = ["grapefruit", "pineapple", "blueberries", "mango", "banana"]
 fruits[1:3]
 ['pineapple', 'blueberries']
 >>> fruits[1:4:2]
 ['pineapple', 'mango']
 fruits[::-1]
 ['banana', 'mango', 'blueberries', 'pineapple', 'grapefruit']
Adding Items to a List
 1. use the append() method to add an element to the end of a Python list.
 fruits = ['apple', 'banana', 'orange']
 fruits.append('cherry')
 print('Updated List:', fruits) -- ['apple', 'banana', 'orange', 'cherry']
 2. insert() method adds an element at the specified index.
 fruits.insert(2, 'cherry')
 print("Updated List:", fruits) -- ['apple', 'banana', 'cherry', 'orange']
 3. use the extend() method to add elements to a list from other list.
 numbers = [1, 3, 5]
 even_numbers = [2, 4, 6]
 numbers.extend(even_numbers)
 print('Updated Numbers:', numbers) -- [1, 3, 5, 2, 4, 6]
Built-In Functions Used on Lists

 len() - The len() function returns the numbers of items in a list.


 sum() - The sum() function returns the sum of numbers in the list.
 any() - The any() function returns True if any of the Boolean values in the list is
True.
 all() - The all() function returns True if all the Boolean values in the list are True,
else returns False.
 sorted() - The sorted() function returns a modified copy of the list while leaving the
original list untouched.
 lakes = ['superior', 'erie', 'huron', 'ontario', 'powell']
 len(lakes)
 lakes_sorted_new = sorted(lakes)
List Methods

 cities = ["oslo", "delhi", "washington", "london", "seattle", "paris", "washington"]


List Methods

 1. >>> dir(list)

 ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__',


'__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__',
'__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__',
'__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__',
'__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__',
'__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__',
'__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend',
'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
Remove an Item From a List

 change the items of a list by assigning new values using the = operator
 colors[2] = 'Blue
 remove an item from a list using the remove() method.
 numbers = [2,4,7,9] numbers.remove(4) [2, 7, 9]
 del statement removes one or more items from a list.
 del numbers[1] del numbers[:] del numbers del numbers[1:3]
 Pop statement Returns and removes item present at the given index –
rightmost item.
 Element = numbers.pop(1) numbers.pop()
Traversing Through a List

 fruits = ['apple', 'banana', 'orange']


 for fruit in fruits:
print(fruit)
for fruit in range(len(fruits))
print(fruit)
print(fruits[fruit])

use the in keyword to check if an item exists in the list.


List Comprehension in Python
 List comprehension offers a concise way to create a new list based on the values of
an existing list.
 numbers = [1, 2, 3, 4]
 square_numbers = [num * num for num in numbers]
 even_numbers = [num for num in range(1, 10) if num % 2 == 0 ]
 even_square_numbers = [num * num for num in numbers if num % 2 == 0 ]
 even_odd_list = ["Even" if num % 2 == 0 else "Odd" for num in numbers]

 List Comprehension with String


 word = "Python"
 vowels = "aeiou"
 result = [char for char in word if char in vowels]
Lambda/Anonymous Function
 lambda : print('Hello World') – created lambda function.
 use the lambda keyword instead of def to create a lambda function.
 Syntax:
 lambda argument(s) : expression
 hi = lambda : print('Hi.. Hello..')
 hi()
 hi_user = lambda name : print('Hi ..Hello..', name)
 Hi_user(„kavitha‟)
lambda function with map() and filter()
 The map() function in Python takes in a function and an iterable (lists, tuples, and strings) as
arguments.
 The function is called with all the items in the list, and a new list is returned, which contains items
returned by that function for each item.
 list1 = [1, 5, 4, 6, 8, 11, 3, 12]
 new_list = list(map(lambda x: x * 2 , list1))
 print(new_list)
 Output: [2, 10, 8, 12, 16, 22, 6, 24]
 The filter() function is called with all the items in the list, and a new list is returned, which contains
items for which the function evaluates to True.
 new_list = list(filter(lambda x: (x%2 == 0) , list1))
 print(new_list)
 # Output: [4, 6, 8, 12]
List Comprehensions vs Lambda Functions

 Along with list comprehensions, we also use lambda functions to work with lists.
 While list comprehension is commonly used for filtering a list based on some conditions, lambda
functions are commonly used with functions like map() and filter().
 They are used for complex operations or when an anonymous function is required.
 square_numbers = [num ** 2 for num in numbers]
 square_numbers = list(map(lambda num : num**2 , numbers))
 Program 6.1: Program to Dynamically Build User Input as a List
 list_1 = list(“Enter list items”)
 print(f"List items are {list_1}")
 list_items = input("Enter list items separated by a space ").split()
 print(f"List items are {list_items}")
 items_of_list = []
 total_items = int(input("Enter the number of items "))
 for i in range(total_items):
 item = input("Enter list item: ")
 items_of_list.append(item)
 print(f"List items are {items_of_list}")
 Program 6.2: Program to Illustrate Traversing of Lists Using the for loop
 fast_food = ["waffles", "sandwich", "burger", "fries"]
 for each_food_item in fast_food:
 print(f"I like to eat {each_food_item}")
 for each_food_item in ["waffles", "sandwich", "burger", "fries"]:
 print(f"I like to eat {each_food_item}")
 Program 6.4: Write Python Program to Sort Numbers in a List in Ascending Order
 Using Bubble Sort by Passing the List as an Argument to the Function Call
 def bubble_sort(list_items):
 for i in range(len(list_items)):
 for j in range(len(list_items)-i-1):
 if list_items[j] > list_items[j+1]:
 temp = list_items[j]
 list_items[j] = list_items[j+1]
 list_items[j+1] = temp
 print(f"The sorted list using Bubble Sort is {list_items}")
 def main():
 items_to_sort = [5, 4, 3, 2, 1]
 bubble_sort(items_to_sort)
 if __name__ == "__main__":
 main()
Nested Lists
 A list inside another list is called a nested list.
 1. >>> asia = [["India", "Japan", "Korea"],
 ["Srilanka", "Myanmar", "Thailand"],
 ["Cambodia", "Vietnam", "Israel"]]
 2. >>> asia[0]
 ['India', 'Japan', 'Korea']
 3. >>> asia[0][1]
 'Japan'
 4. >>> asia[1][2] = "Philippines"
The del Statement
 You can remove an item from a list based on its index rather than its value. The difference
 between del statement and pop() function is that the del statement does not return any
value
 while the pop() function returns a value. The del statement can also be used to remove
 slices from a list or clear the entire list.
 1. >>> a = [5, -8, 99.99, 432, 108, 213]
 2. >>> del a[0]
 3. >>> a
 [-8, 99.99, 432, 108, 213]
 4. >>> del a[2:4]
 5. >>> a
 [-8, 99.99, 213]
 6. >>> del a[:]
PYTHON PROGRAMMING
UNIT IV - FILES

Dr. D.Kavitha
Files
 Two types of files – Text files and Binary files.
 In text file, an End-of-Line (EOL) character is placed at the end of each line.
 An End-of-File (EOF) marker is placed after the final character, which signals the
end of the file.
Files
File Path
 file path -- which is basically a route so that the user or the program knows where the file is located.
 Fully Qualified Path and Relative Path
Creating and Reading Text Data
 open() – open a file.
 file_handler = open(filename, mode) f1 = open(“example.txt",”x")
 close() –
 file_handler.close() f1.close()
 Use of with Statements to Open and Close Files
 with open (file, mode) as file_handler: with open(“a.txt”,w+) as f1, open(“b.txt”,w+) as f2:
 Statement_1 .
 Statement_2 .
 with open(“example.txt",”x") as f1:
 for line in f1:
 print(line)
 f1.close()
Mode Description
File Object Attributes
 When the Python open() function is called, it returns a file object called a file handler(f1). Using this
file handler, you can retrieve information about various file attributes. For example,
 1. >>> f1 = open("computer.txt", "w")
 2. >>> print(f"File Name is {f1.name}") File Name is computer.txt
 3. >>> print(f"File State is {f1.closed}") File State is False
 4. >>> print(f"File Opening Mode is {f1.mode}") File Opening Mode is w

 Attribute Description
 f1.closed It returns a Boolean True if the file is closed or False otherwise.
 f1.mode It returns the access mode with which the file was opened.
 f1.name It returns the name of the file.
File Methods to Read and Write Data
 When you use the open() function a file object is created. Here is the list of methods that can be
called on this object

 read() -- file_handler.read([size]) -- This method is used to read the contents of a file up to a


size and return it as a string. The argument size is optional, and, if it is not specified, then the
entire contents of the file will be read and returned.
 print(f1.read(2))
 readline() -- file_handler.readline() -- This method is used to read a single line in file.
 print(f1.readline(), end=“ ")
 readlines() -- file_handler.readlines() -- This method is used to read all the lines of a file as list
items.
 print(f1.readlines(), end=“ ")
 write() -- file_handler.write(string) -- This method will write the contents of the string to the file,
returning the number of characters written. If you want to start a new line, you must include the
new line character.
 f1.write("Moon is a natural satellite")
File Methods to Read and Write Data
 writelines() -- file_handler.writelines(sequence) -- This method will write a sequence of
strings to the file.
 f1.writelines(["Moon is a natural satellite", " ", "of the earth"])
 tell() -- file_handler.tell() -- This method returns an integer giving the file handler‟s
current position within the file, measured in bytes from the beginning of the file.
 f1.tell()
 seek() -- file_handler.seek(offset,from_what) -- This method is used to change the file
handler‟s position. The position is computed from adding offset to a reference point. The
reference point is selected by the from_what argument. A from_what value of 0 measures
from the beginning of the file, 1 uses the current file position, and 2 uses the end of the file
as the reference point. If the from_what argument is omitted, then a default value of 0 is
used, indicating that the beginning of the file itself is the reference point.
 f1.seek(5)
File Methods to Read and Write Data
File Methods to Read and Write Data
Reading and Writing Binary Files
The Pickle Module
 Pickle -- This is a module that can take almost any Python object and convert it to a string
representation; this process is called pickling.
 Reconstructing the object from the string representation is called unpickling.

 If you have an object x and a file object f, which has been opened for writing, the simplest way to
pickle the object is, pickle.dump(x, f)
 The dump() method writes a pickled representation of object x to the open file object f.

 If f is a file object, which has been opened for reading, then the simplest way to unpickle the object
is, x = pickle.load(f)
 The load() method reads a pickled object representation from the open file object f and return the
reconstituted object hierarchy specified therein.
 Pickling is the standard way to make Python objects that can be stored and reused by other programs
or by a future invocation of the same program;
Reading and Writing CSV Files
 CSV (Comma Separated Values) format is the most common import and export format for
spreadsheets and databases. Since a comma is used to separate the values, this file format is
aptly named Comma Separated Values
Reading and Writing CSV Files
 CSV files have .csv extensions

 To read from a CSV file use csv.reader() method. The syntax is,
 csv.reader(csvfile)

 To write to a CSV file, use the csv.writer() method. The syntax is,
 csv.writer(csvfile)

 The syntax for writerow() method is,


 csvwriter.writerow(row)
Reading and Writing CSV Files
 The syntax for writerows() method is,
 csvwriter.writerows(rows)

 The syntax for DictReader is,


 class csv. DictReader(f, fieldnames=None, restkey = None)

 The syntax for DictWriter is,


 class csv. DictWriter(f, fieldnames, extrasaction=‘raise’)
Reading and Writing CSV Files

 1. import csv
 2. def main():
 3. with open('biostats.csv', newline='') as csvfile:
 4. csv_reader = csv.reader(csvfile)
 5. print("Print each row in CSV file")
 6. for each_row in csv_reader:
 7. print(",".join(each_row))
 8. if __name__ == "__main__":
 9. main()
Python os and os.path Modules
 Python os module provides a portable way of using operating system dependent functionality.
 For accessing the filesystems, use the os module.
 To manipulate paths, use the os.path module.
Summary

 Python supports two basic file types, namely text files and binary files.

 • File objects can be used to read/write data to/from files. You can open a file with mode 'r' for
reading, 'w' for writing, and 'a' for appending.

 • The read(), readline(), and readlines() methods are used to read data from a file.

 • The write() and writes() methods are used to write data to a file.

 • The file object should be closed after the file is processed to ensure that the content

 is saved properly.

 • The dictionary data can be read and written to a CSV file using DictReader() and DictWriter()
classes.

 • The os Module methods are used to perform some important processing on files.
Object-Oriented Programming

 Classes and Objects


 A class is a blueprint from which individual objects are created.
 An object is a bundle of related state (variables) and behavior (methods).
 Objects contain variables, which represents the state of information about the thing you are trying to
model, and the methods represent the behavior or functionality
Creating Classes/objects in Python
 class ClassName:
 <statement-1>
 ...
 <statement-N>
 Class course:
 Name = „‟

 object_name = ClassName(argument_1, argument_2, ….., argument_n)


 Course1 = course()
 Class abc:
 a=10
 Obj = abc()
 Print(obj.a)
The Constructor Method
 class abc:
 a=10
 def display(self):
 print(f"Sample class method. Value is {self.a}")
 obj = abc()
 print(obj.a)
 obj.display()

 class abcd:
 def __init__(self,a):
 self.a = a
 print(f"Sample class method. Value is {self.a}")
 obj = abcd(10)
The Constructor Method
 The __init__() method defines and initializes the instance variables. It is invoked as soon as an object of a
class is instantiated.
 The number of arguments during the instantiation of the class object should be equivalent to the number of
parameters in __init__() method (excluding the self parameter).
 All classes have a function called __init__(), which is always executed when the class is being initiated.
 Use the __init__() function to assign values to object properties, or other operations that are necessary to
do when the object is being created

 Class instantiation uses function notation, wherein the class name is followed by parentheses ()
 The self parameter is a reference to the current instance of the class, and is used to access variables that
belong to the class.
 It does not have to be named self, you can call it whatever you like, but it has to be the first parameter of
any function in the class.
 The remaining parameter variables must be supplied as arguments in the calling method
Classes with Multiple Objects
 class Person:
def __init__(self, name, age):
self.name = name
self.age = age

p1 = Person("John", 36)
print(p1.name)
print(p1.age)
Inheritance
 A class that is used as the basis for inheritance is called a superclass or base class or parent
class
 A class that inherits from a base class is called a subclass or derived class or child class .
 A derived class inherits variables and methods from its base class while adding additional
variables and methods of its own.
 class DerivedClassName(BaseClassName):
 <statement-1>
 ...
 <statement-N>
Inheritance
Polymorphism

 Polymorphism means that you can have multiple


 classes where each class implements the same variables or methods in different ways.
 Polymorphism takes advantage of inheritance in order to make this happen
 Difference between inheritance and polymorphism is, while inheritance is implemented on classes,
polymorphism is implemented on methods.
Polymorphism
Unit -5
JSON and XML
 JSON (JavaScript Object Notation) and XML (EXtensible Markup Language) standards are
commonly used for transmitting data in web applications
Using JSON with Python

 JSON (JavaScript Object Notation) is a lightweight text-based data-interchange format, which


was popularized by Douglas Crockford.
 JSON is plain text written in JavaScript object notation
 JSON is used to send data between computers
 JSON is language independent
 Since the format is text only, JSON data can easily be sent between computers, and used by
any programming language.
 The built-in data types in JSON are strings, numbers, booleans (i.e., true and false), null,
objects, and arrays.
 {
"employee":{"name":"John", "age":30, "city":"New York"}
}
 {
"employees":["John", "Anna", "Peter"]
}
 Parsing JSON Data
 Python provides a JSON module that allows you to parse JSON data easily:
 import json

# parse a JSON string


json_string = '{"name": "John", "age": 30, "city": "New York"}'
data = json.loads(json_string) # returns a dictionary
 In this example, we imported the JSON module and parsed a JSON string
using the loads() method. The data variable contains a dictionary object
that represents the parsed JSON data.
 Accessing JSON Data
 Once you have the JSON data as a Python object, you can access it
using Python‟s dictionary syntax:
 print(data['name']) # access a value by key

for key, value in data.items(): # loop through all key-value pairs


print(key, value) # print key and value
 In this example, we accessed the values in the dictionary using
their keys. We also demonstrated how to loop through all key-value
pairs in the dictionary.
 JavaScript has a built in function for converting JSON strings into JavaScript objects:
 JSON.parse()

 JavaScript also has a built in function for converting an object into a JSON string:
 JSON.stringify()
NumPy with Python
 NumPy is the fundamental package for scientific computing with Python. It stands for
“Numerical Python.” It supports:
 • N-dimensional array object
 • Broadcasting functions
 • Tools for integrating C/C++ and Fortran code
 • Useful linear algebra, Fourier transform, and random number capabilities.
 NumPy‟s main object is the homogeneous multidimensional array
 NumPy‟s array class is called ndarray or array.
 the individual data items are called elements
 Arrays can be made up of any number of dimensions called as axes.
 Length(dimension) – the total number of elements in that direction.
 The size (array) -- total number of elements contained in an array in all the dimension.
 The size of NumPy arrays are fixed;
 All the rows are indicated by Axis-0 and all the columns are indicated by Axis-1.
 the indexes range from 0 to length – 1.
 Array indexes are 0-based. That is, if the length of a dimension is n, the index values
range from 0 to n – 1.
NumPy Arrays Creation Using array() Function

 import numpy as np
 n_array = np.array([1,2,3,4])
 type(n_array) -- array([1, 2, 3, 4])
 n_array.dtype -- dtype('int32')
 array_list = np.array([[1,2,3], [4,5,6]]) -- array([[1, 2, 3], [4, 5, 6]])
 array_tuple = np.array(((1,2,3), (4,5,6))) -- array([[1, 2, 3], [4, 5, 6]])
 array_dtype = np.array([1,2,3,4], dtype = np.float64) -- array([1., 2., 3., 4.])
Array Attributes
Arrays creation with Initial values
Indexing, Slicing
Indexing, Slicing
Basic Arithmetic Operations

You might also like