Part 2 of article series can be found here.
A list is a data structure which contains a series of individual data. Values stored in a list can be of any type such as string, integer, float, or list. Lists contain a comma separated ordered sequence of values, enclosed in square brackets. For example:
Subjects = \[“Hindi”, “English”, “Maths”, “History”\]
By default, the elements inside the list have the index starting from 0. We can extract the values by passing the index inside [ ‘ index ’].
> subjects =["Hindi", "English", "Maths", "History"]
> subjects
['Hindi', 'English', 'Maths', 'History']
> subjects[2]
'Maths'
We can also make two-dimensional lists by passing a list inside another list.
>>> subjectMarks =[["Hindi",55], ["English",67], ["Maths",98], ["History", 76]]
> subjectMarks
[['Hindi', 55], ['English', 67], ['Maths', 98], ['History', 76]]
> subjectMarks[3]
['History', 76]
> list1 = ['Red', 'Green']>>> list2 = [10, 20, 30]
> list2 * 2 #multiplication operator *[10, 20, 30, 10, 20, 30]
> list1 = list1 + ['Blue'] #concatenation operator +> list1['Red', 'Green', 'Blue']
> len(list1) #length operator3
> list2[-1] # indexing form end30
>>> list2[0:2] # Slicing : Syntax start:end:inc[10, 20]
> min(list2) #minimum function10
> max(list2) #maximum operator30
>>> sum(list2) #sum function60
> 40 in list2 # Membership operator inFalse
> vowels ='aeiou'
>list(vowels)
['a', 'e', 'i', 'o', 'u']
1. Append Function:
The append function inserts the object passed to it at the end of the list. For example:
>>> a = [1,2,4,5,67,23]> a.append(34)> print(a)[1, 2, 4, 5, 67, 23, 34] #at the end of the list
2. Extend Function:
The extend function takes a series argument and appends the elements of the sequence at the end of the list.
>>> a = [10,20,30,40]>>> a.extend([50,60])> print(a)[10, 20, 30, 40, 50, 60]
3. Count Function:
The count function returns the count of the number of times the object passed as an argument appears in the list. For example:
>>> a = [10, 20, 30, 10, 50, 20, 60, 20, 30,55]> print("20 occurred for ", a.count(20), " times")20 occurred for 3 times
4. Pop Function:
The pop function returns the element from the list whose index is passed as an argument, while removing it from the list. For example:
>>> a = [10, 20, 30, 10, 50, 20, 60, 20, 40, 55]> a.pop(5)20> a[10, 20, 30, 10, 50, 60, 20, 40, 55]
5. Remove Function:
This function takes the value which is to be removed from the list and deletes the first occurrence of that element. For example:
>>> a = [10, 20, 30, 20, 60, 20, 30, 55]> a.remove(55)> a[10, 20, 30, 20, 60, 20, 30] # 55 first occured at index:8
6. Del Function:
The del operator is used to remove a subsequence of elements (start:end:increment) from a list, it is used for deleting elements in the given index range. For example:
>>> a = [10, 20, 30, 20, 60, 20, 30, 55]>>> del a[2:6:3]> a[10, 20, 20, 60, 30, 55]
7. Index Function:
If we have two lists, names (the list of the names of students) and rollNums (the list of corresponding roll numbers):
names = ['Ram', 'Shyam', 'Sita', 'Gita', 'Sita’]; rollNums = [1, 2, 3, 4, 5]
To remove a student, ‘Shyam’ from the lists, we cannot apply the function remove as we do not know the roll number of ‘Shyam’. However, since there is a correspondence between student names and their roll numbers, knowing the index of a student in the list names will solve the problem. Python function index can be used for finding the index of a given value in the list.
> names = ['Ram', 'Shyam', 'Sita', 'Gita', 'Sita']>>> rollNums = [1, 2, 3, 4, 5]> rollNums.pop(names.index('Shyam'))2> names.remove('Shyam')> print(names, rollNums)['Ram', 'Sita', 'Gita', 'Sita'] [1, 3, 4, 5]
8. Insert Function:
The insert function can be used to insert an object at a specified index. This function takes two arguments: the index where an object is to be inserted and the object itself. For example:
> names = ['Ram', 'Sita', 'Gita', 'Sita']> names.insert(2, 'Shyam') # insert shyam at index 2> names['Ram', 'Sita', 'Shyam', 'Gita', 'Sita']
9. Reverse Function:
The reverse function reverses the order of the elements in a list. For example:
> names = ['Ram', 'Shyam', 'Sita', 'Gita', 'Sita']> names.reverse()> names['Sita', 'Gita', 'Sita', 'Shyam', 'Ram'] #reversed list
10. Sort Function:
The sort function can be used to arrange the elements in a list in ascending order. For descending order, we just use the reverse function as discussed above.
> names = ['Ram', 'Shyam', 'Sita', 'Gita']> names.sort()> names['Gita', 'Ram', 'Shyam', 'Sita']
Unlike lists, tuples, and strings, a dictionary is an unordered sequence of key-value pairs. Indices in a dictionary can be of any immutable type and are called keys. Beginning with an empty dictionary, we create a dictionary of month_number-month_name pairs as follows:
> months = {1: 'Jan', 2: 'Feb', 3: 'Mar', 4: 'Apr'}>>> type(months)<class 'dict'>
> price = {'tomato':40, 'cucumber':30,... 'potato':20, 'cauliflower':70,... 'cabbage':50, 'lettuce':40, 'raddish':30,... 'carrot':20, 'peas':80}>> price['potato']20> price['lettuce']40> price.keys() #returns keysdict_keys(['tomato', 'cucumber', 'potato', 'cauliflower', 'cabbage', 'lettuce', 'raddish', 'carrot', 'peas'])
Del Function: We may remove a key-value pair from a dictionary using del operator. For example:
> winter = {11:'November ', 12:... 'December', 1:'January', 2:'February'}> del winter[11] #removing a key-value pair> winter{12: 'December', 1: 'January', 2: 'February'}
Clear Function: To remove all the key–value pairs in a dictionary, we use the clear function. Note that while assigning an empty dictionary {} creates a new object.
> winter.clear()> winter{}
Update Function:
The update function is used to insert all the key–value pairs of another dictionary into a dictionary. For example:
> passwords = {'Ram':'ak@607',... 'Shyam':'rou.589', 'Gita':'yam@694'}> morePasswords = {'Raman':'vi97@4',... 'Kishore':'23@0jsk'}> passwords.update(morePasswords) #adds at the end of the list.> passwords{'Ram': 'ak@607', 'Shyam': 'rou.589', 'Gita': 'yam@694', 'Raman': 'vi97@4', 'Kishore': '23@0jsk'}
Copy Function:
To create a shallow copy of a dictionary object, we make use of the copy function. For example:
>>> newPasswords = morePasswords.copy()>>> id(newPasswords), id(morePasswords) #returns the IDs of both list(1602834728984, 1602834728664) #same
demo_list = [] #empty list
len_list = int(input("Enter the length of list: ")) #lenght of the list.
for i in range(0,len_list):x = int(input("Enter the elements: "))demo_list.append(x) #inserting element inside the list
#to print the elements of the list we use the same conceptfor i in range(0,len_list):print(demo_list[i], end = ' ')
Programs that we have developed so far take the input in an interactive manner, such as that the data remains in the memory only for the duration of the program. But, we can store the values which are usually stored inside the disk permanently, so that they are available when required. For example, to verify the user we can store the username and password inside a file, which can be used anytime. Files provide a means to store the data permanently.
File is a medium of communication between the program and the outside world. Files can be used where we need to store data permanently. We can apply various kinds of built-in functions to the files, like read(), write(), append(), etc. Before doing any operation on file we need to open the file using open() function. Modes for opening a file:
read®: to read the file
write(w): to write to the file
append(a): to write at the end of the file
f = open(file_name, access_mode) By default file is opened in read mode.
And by default Python provides the file_name as the directory in which the file is stored.
To use the read and write functions we need to use the following notation: the name of the object followed by the dot(.) operator. Learn more about file handling here.
f = open('python', 'w') #creates a file named python.
f.write('''Python:Python is an interactive programming language.Simple syntax of the language makes Python programs easy to read and write.''')
OUTPUT
Reading a file:
f=open('python', 'r')
print(f.read())
Errors occur when something goes wrong. We have encountered many errors in our program, such as division by zero, index out of bound, invalid cast operation, etc. Errors in Python can be classified as syntax errors and exceptions. A syntax error occurs when a rule of Python grammar is violated. For example:
>>>print('Hello World!)
File "<stdin>", line 1
print('Hello World! )
SyntaxError: EOL *while* scanning string literal
>>> for i in range(0,10)File "<stdin>", line 1for i in range(0,10)
^SyntaxError: invalid syntax
TYPES OF ERRORS IN PYTHON
1. NameError: This exception occurs whenever a name that appears in a statement is not found globally.
>>> number = Input('Enter the test number')Traceback (most recent call last):File "<stdin>", line 1, in <module>NameError: name 'Input' is not defined
2. TypeError : This exception occurs when an operation or function is applied to an object of inappropriate type. For example:
> 'sum of 2 and 3 is ' + 5Traceback (most recent call last):File "<stdin>", line 1, in <module>TypeError: can only concatenate str (not "int") to str
3. ValueError: This exception occurs whenever an inappropriate argument value, even though of correct type, is used in a function call. For example:
> int('Hello World!')Traceback (most recent call last):File "<stdin>", line 1, in <module>ValueError: invalid literal for int() with base 10: 'Hello World!'
4. ZeroDivisionError : As the name suggests, this exception occurs when we try to perform numeric division in which the denominator happens to be zero. For example:
>>> 1024 / (2+3-5)Traceback (most recent call last):File "<stdin>", line 1, in <module>ZeroDivisionError: division by zero
5. OSError : This exception occurs whenever there is a system related error such as disk full or an error related to input/output. For example, opening a non-existent file for reading or reading a file opened in write mode:
> f = open("documents.txt")Traceback (most recent call last):File "<stdin>", line 1, in <module>FileNotFoundError: [Errno 2] No such file or directory: 'documents.txt'
6. IndexError: This error occurs when we try to access the index which is not present.
> colors = ['red', 'green', 'blue']> colors[3]Traceback (most recent call last):File "<stdin>", line 1, in <module>IndexError: list index out of range
The above exceptions are unhandled exceptions. To prevent the program’s abrupt termination whenever an exception is raised, we need to handle it by catching and taking appropriate action using try and except clauses.
Try block comprises the statement that might have the potential to raise an exception, and except block comprises the statement that describes the action to be taken whenever any exception is raised.
1 2 3 4try: #statements having potential to raise an exception except: #action to be performed when exception is raised
Example: Index error
1
2
3
4
5
6
7
pr_langs = ['python', 'c++', 'c#', 'java', 'c']
try:
print(pr_langs[5])
except:
print('Index out of bound')
print('Enter a valid index')
Tracking a raised exception:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16import sys def main(): '' ' Objective: To open a file for reading Input Parameter: None Return: None '' ' try: f = open('Temp_file', 'r') #opening a file which is not available except IOError as err: #input output error as err print('Problem with Input Output...', err) print(sys.exc_info()) #prints the type of error main()