PROBLEM SOLVING USING PYTHON [22PLC151/251] MODULE-4 PYTHON LIST A list in Python is used to store the sequence of various types of data. A list can be defined as a collection of values or items of different types. Python lists are mutable type which implies that we may modify its element after it has been formed. The items in the list are separated with the comma (,) and enclosed with the square brackets []. List Declaration: Code: # a simple list list1 = [1, 2, "Python", "Program", 15.9] list2 = ["Amy", "Ryan", "Henry", "Emma"] # printing the list print(list1) print(list2) # printing the type of list print(type(list1)) print(type(list2)) Output: [1, 2, 'Python', 'Program', 15.9] ['Amy', 'Ryan', 'Henry', 'Emma'] < class ' list ' > < class ' list ' > Characteristics of Lists: The list has the following characteristics: The lists are ordered. The element of the list can access by index. The lists are the mutable type. The lists are mutable types. A list can store the number of various elements. 1 Dept. of ECE, NHCE PROBLEM SOLVING USING PYTHON [22PLC151/251] List Indexing and Splitting: The indexing is processed in the same way as it happens with the strings. The elements of the list can be accessed by using the slice operator []. The index starts from 0 and goes to length - 1. The first element of the list is stored at the 0th index, the second element of the list is stored at the 1st index, and so on. We can get the sub-list of the list using the following syntax. list_varible[start:stop:step] The start denotes the starting index position of the list. The stop denotes the last index position of the list. The step is used to skip the nth element within a start:stop The initial index is represented by the start parameter, the ending index is determined by the step, and also the number of elements which are "stepped" through is the value of the end parameter. In the absence of a specific value for step, the default value equals 1. Inside the resultant SubList, the item also with index start would be present, but the one with the index finish will not. A list's initial element seems to have the index of 0. Consider the following example: Code: list = [1,2,3,4,5,6,7] print(list[0]) print(list[1]) print(list[2]) print(list[3]) # Slicing the elements 2 Dept. of ECE, NHCE PROBLEM SOLVING USING PYTHON [22PLC151/251] print(list[0:6]) # By default, the index value is 0 so its starts from the 0th element and go for index 1. print(list[:]) print(list[2:5]) print(list[1:6:2]) Output: 1 2 3 4 [1, 2, 3, 4, 5, 6] [1, 2, 3, 4, 5, 6, 7] [3, 4, 5] [2, 4, 6] In contrast to other languages, Python gives you the option to employ negative indexing as well. From the right, the negative indices are counted. The final element on the right-hand side of the list is represented by the index -1, followed by the next member on the left at the index -2, and so on until the last element on the left is reached. Let's have a look at the following example where we will use negative indexing to access the elements of the list. Code # negative indexing example list = [1,2,3,4,5] print(list[-1]) print(list[-3:]) print(list[:-1]) print(list[-3:-1]) 3 Dept. of ECE, NHCE PROBLEM SOLVING USING PYTHON [22PLC151/251] Output: 5 [3, 4, 5] [1, 2, 3, 4] [3, 4] Lists are the most versatile data structures in Python since they are mutable, and their values can be updated by using the slice and assignment operator. Python also provides append() and insert() methods, which can be used to add values to the list. Consider the following example to update the values inside the list. Code # updating list values list = [1, 2, 3, 4, 5, 6] print(list) # It will assign value to the value to the second index list[2] = 10 print(list) # Adding multiple-element list[1:3] = [89, 78] print(list) # It will add value at the end of the list list[-1] = 25 print(list) Output: [1, 2, 3, 4, 5, 6] [1, 2, 10, 4, 5, 6] [1, 89, 78, 4, 5, 6] [1, 89, 78, 4, 5, 25] The list elements can also be deleted by using the del keyword. Python also provides us the remove() method if we do not know which element is to be deleted from the list. Consider the following example to delete the list elements. 4 Dept. of ECE, NHCE PROBLEM SOLVING USING PYTHON [22PLC151/251] Code list = [1, 2, 3, 4, 5, 6] print(list) # It will assign value to the value to second index list[2] = 10 print(list) # Adding multiple element list[1:3] = [89, 78] print(list) # It will add value at the end of the list list[-1] = 25 print(list) Output: [1, 2, 3, 4, 5, 6] [1, 2, 10, 4, 5, 6] [1, 89, 78, 4, 5, 6] [1, 89, 78, 4, 5, 25] Python List Operations: The concatenation (+) and repetition (*) operators work in the same way as they were working with the strings. The different operations of list are 1. Repetition 2. Concatenation 3. Length 4. Iteration 5. Membership Let's see how the list responds to various operators. 1. Repetition The repetition operator enables the list elements to be repeated multiple times. Code # repetition of list # declaring the list list1 = [12, 14, 16, 18, 20] 5 Dept. of ECE, NHCE PROBLEM SOLVING USING PYTHON [22PLC151/251] # repetition operator * l = list1 * 2 print(l) Output: [12, 14, 16, 18, 20, 12, 14, 16, 18, 20] 2. Concatenation It concatenates the list mentioned on either side of the operator. Code # concatenation of two lists # declaring the lists list1 = [12, 14, 16, 18, 20] list2 = [9, 10, 32, 54, 86] # concatenation operator + l = list1 + list2 print(l) Output: [12, 14, 16, 18, 20, 9, 10, 32, 54, 86] 3. Length It is used to get the length of the list Code # size of the list # declaring the list list1 = [12, 14, 16, 18, 20, 23, 27, 39, 40] # finding length of the list len(list1) Output: 9 4. Iteration The for loop is used to iterate over the list elements. Code 6 Dept. of ECE, NHCE PROBLEM SOLVING USING PYTHON [22PLC151/251] # iteration of the list # declaring the list list1 = [12, 14, 16, 39, 40] # iterating for i in list1: print(i) Output: 12 14 16 39 40 5. Membership It returns true if a particular item exists in a particular list otherwise false. Code # membership of the list # declaring the list list1 = [100, 200, 300, 400, 500] # true will be printed if value exists # and false if not print(600 in list1) print(700 in list1) print(1040 in list1) print(300 in list1) print(100 in list1) print(500 in list1) Output: False False False True True True 7 Dept. of ECE, NHCE PROBLEM SOLVING USING PYTHON [22PLC151/251] Iterating a List A list can be iterated by using a for - in loop. A simple list containing four strings, which can be iterated as follows. Code: # iterating a list list = ["John", "David", "James", "Jonathan"] for i in list: # The i variable will iterate over the elements of the List and contains each element in each iteration. print(i) Output: John David James Jonathan Adding Elements to the List: Python provides append() function which is used to add an element to the list. However, the append() function can only add value to the end of the list. Consider the following example in which, we are taking the elements of the list from the user and printing the list on the console. Code #Declaring the empty list l =[] #Number of elements will be entered by the user n = int(input("Enter the number of elements in the list:")) # for loop to take the input for i in range(0,n): # The input is taken from the user and added to the list as the item l.append(input("Enter the item:")) print("printing the list items..") # traversal loop to print the list items for i in l: print(i, end = " ") 8 Dept. of ECE, NHCE PROBLEM SOLVING USING PYTHON [22PLC151/251] Output: Enter the number of elements in the list:10 Enter the item:32 Enter the item:56 Enter the item:81 Enter the item:2 Enter the item:34 Enter the item:65 Enter the item:09 Enter the item:66 Enter the item:12 Enter the item:18 printing the list items.. 32 56 81 2 34 65 09 66 12 18 Removing Elements from the List: Python provides the remove() function which is used to remove the element from the list. Consider the following example to understand this concept. Example Code list = [0,1,2,3,4] print("printing original list: "); for i in list: print(i,end=" ") list.remove(2) print("\nprinting the list after the removal of first element...") for i in list: print(i,end=" ") Output: printing original list: 01234 printing the list after the removal of first element... 0134 9 Dept. of ECE, NHCE PROBLEM SOLVING USING PYTHON [22PLC151/251] Python List Built-in Functions Python provides the following built-in functions, which can be used with the lists. 1. len() 2. max() 3. min() len( ) It is used to calculate the length of the list. Code # size of the list # declaring the list list1 = [12, 16, 18, 20, 39, 40] # finding length of the list len(list1) Output: 6 Max( ) It returns the maximum element of the list Code # maximum of the list list1 = [103, 675, 321, 782, 200] # large element in the list print(max(list1)) Output: 782 Min( ) It returns the minimum element of the list Code 10 Dept. of ECE, NHCE PROBLEM SOLVING USING PYTHON [22PLC151/251] # minimum of the list list1 = [103, 675, 321, 782, 200] # smallest element in the list print(min(list1)) Output: 103 List Comprehension: List comprehension offers a shorter syntax when you want to create a new list based on the values of an existing list. The Syntax: newlist = [expression for item in iterable if condition == True] The return value is a new list, leaving the old list unchanged. Condition The condition is like a filter that only accepts the items that valuate to True. Iterable The iterable can be any iterable object, like a list, tuple, set etc. Expression The expression is the current item in the iteration, but it is also the outcome, which you can manipulate before it ends up like a list item in the new list: Example: Based on a list of fruits, you want a new list, containing only the fruits with the letter "a" in the name. Without list comprehension you will have to write a for statement with a conditional test inside: fruits = ["apple", "banana", "cherry", "kiwi", "mango"] newlist = [] for x in fruits: if "a" in x: newlist.append(x) 11 Dept. of ECE, NHCE PROBLEM SOLVING USING PYTHON [22PLC151/251] print(newlist) With list comprehension you can do all that with only one line of code: fruits = ["apple", "banana", "cherry", "kiwi", "mango"] newlist = [x for x in fruits if "a" in x] print(newlist) 12 Dept. of ECE, NHCE PROBLEM SOLVING USING PYTHON [22PLC151/251] TUPLES IN PYTHON Python Tuple is a collection of objects separated by commas. In some ways, a tuple is similar to a list in terms of indexing, nested objects, and repetition but a tuple is immutable, unlike lists which are mutable. A Python Tuple is a group of items that are separated by commas. The indexing, nested objects, and repetitions of a tuple are somewhat like those of a list, however unlike a list, a tuple is immutable. Example: ("Suzuki", "Audi", "BMW"," Skoda ") is a tuple. Features of Python Tuple: Tuples are an immutable data type, which means that once they have been generated, their elements cannot be changed. Since tuples are ordered sequences, each element has a specific order that will never change. Creating of Tuple: To create a tuple, all the objects (or "elements") must be enclosed in parenthesis (), each one separated by a comma. The parentheses are optional, however, it is a good practice to use them. A tuple can have any number of items and they may be of different types (integer, float, list, string, etc.). 13 Dept. of ECE, NHCE PROBLEM SOLVING USING PYTHON [22PLC151/251] Create a Python Tuple With one Element In Python, creating a tuple with one element is a bit tricky. Having one element within parentheses is not enough. We will need a trailing comma to indicate that it is a tuple. var1 = ("Hello") # string var2 = ("Hello",) # tuple Updating Tuples Tuples are immutable which means you cannot update or change the values of tuple elements. You are able to take portions of existing tuples to create new tuples as the following example demonstrates − 14 Dept. of ECE, NHCE PROBLEM SOLVING USING PYTHON [22PLC151/251] Delete Tuple Elements Removing individual tuple elements is not possible. There is, of course, nothing wrong with putting together another tuple with the undesired elements discarded. To explicitly remove an entire tuple, just use the del statement. For example − This produces the following result. Note an exception raised, this is because after del tup tuple does not exist any more − 15 Dept. of ECE, NHCE PROBLEM SOLVING USING PYTHON [22PLC151/251] Basic Tuples Operations Tuples respond to the + and * operators much like strings; they mean concatenation and repetition here too, except that the result is a new tuple, not a string. Access Python Tuple Elements Like a list, each element of a tuple is represented by index numbers (0, 1, ...) where the first element is at index 0. We use the index number to access tuple elements. For example, 1. Indexing We can use the index operator [] to access an item in a tuple, where the index starts from 0.So, a tuple having 6 elements will have indices from 0 to 5. Trying to access an index outside of the tuple index range(6,7,... in this example) will raise an IndexError. The index must be an integer, so we cannot use float or other types. This will result in TypeError. In the above example, letters[0] - accesses the first element 16 Dept. of ECE, NHCE PROBLEM SOLVING USING PYTHON [22PLC151/251] letters[5] - accesses the sixth element 2. Negative Indexing Python allows negative indexing for its sequences. The index of -1 refers to the last item, -2 to the second last item and so on. For example, In the above example, letters[-1] - accesses last element letters[-3] - accesses third last element Tuple Functions There are some methods and functions which help us to perform different tasks in a tuple. Therefore, we can call them tuple functions. Furthermore, these tuple functions make our work easy and efficient. Besides, there are a number of functions such as cmp(), len(), max(), min(), tuple(), index(), count(), sum(), any(), all(), sorted(), reversed(). The len() Function This function returns the number of elements present in a tuple. Moreover, it is necessary to provide a tuple to the len() function. The count() Function 17 Dept. of ECE, NHCE PROBLEM SOLVING USING PYTHON [22PLC151/251] This function will help us to fund the number of times an element is present in the tuple. Furthermore, we have to mention the element whose count we need to find, inside the count function. The index() Function The tuple index() method helps us to find the index or occurrence of an element in a tuple. This function basically performs two functions: Giving the first occurrence of an element in the tuple. Raising an exception if the element mentioned is not found in the tuple. 18 Dept. of ECE, NHCE PROBLEM SOLVING USING PYTHON [22PLC151/251] The sorted() Function This method takes a tuple as an input and returns a sorted list as an output. Moreover, it does not make any changes to the original tuple. The min(), max(), and sum() Tuple Functions min(): gives the smallest element in the tuple as an output. Hence, the name is min(). max(): gives the largest element in the tuple as an output. Hence, the name is max(). sum(): gives the sum of the elements present in the tuple as an output. 19 Dept. of ECE, NHCE PROBLEM SOLVING USING PYTHON [22PLC151/251] Advantages of Tuple over List in Python Since tuples are quite similar to lists, both of them are used in similar situations. However, there are certain advantages of implementing a tuple over a list: We generally use tuples for heterogeneous (different) data types and lists for homogeneous (similar) data types. Since tuples are immutable, iterating through a tuple is faster than with a list. So there is a slight performance boost. Tuples that contain immutable elements can be used as a key for a dictionary. With lists, this is not possible. If you have data that doesn't change, implementing it as tuple will guarantee that it remains write-protected. 20 Dept. of ECE, NHCE PROBLEM SOLVING USING PYTHON [22PLC151/251] Bonus Questions for Practice 21 Dept. of ECE, NHCE PROBLEM SOLVING USING PYTHON [22PLC151/251] Write a Python program to find the repeated items of a tuple. #create a tuple tuplex = 2, 4, 5, 6, 2, 3, 4, 4, 7 print(tuplex) #return the number of times it appears in the tuple. count = tuplex.count(2) print(count) Write a Python program which accepts a sequence of comma-separated numbers from user and generate a list and a tuple with those numbers. values = input("Input some comma seprated numbers : ") list = values.split(",") tuple = tuple(list) print('List : ',list) print('Tuple : ',tuple) Output: Write a python program to print sum of tuple elements. test_tup = (7, 5, 9, 1, 10, 3) print("The original tuple is : " + str(test_tup)) res = sum(list(test_tup)) 22 Dept. of ECE, NHCE PROBLEM SOLVING USING PYTHON [22PLC151/251] print("The sum of all tuple elements are : " + str(res)) # printing result Write a python program to Check if the given element is present in tuple or not. test_tup = (10, 4, 5, 6, 8) print("The original tuple : " + str(test_tup)) N = int(input("value to be checked:")) for ele in test_tup : if N == ele : print("yes the value is present") break else: print("the value is not present") break Write a Python program to add an item in the tuple. tup=(1,2,3,4) #original tuple print("Original tuple before adding element is: ",tup) l=list(tup) l.append(5) print("After adding element ",tuple(l)) 23 Dept. of ECE, NHCE