OBJECTIVE - PK
LAB # 08 ListingOBJECTIVEExploring list/arrays in python programming.THEORYA list can store a collection of data of any size. It is a collection which is ordered and changeable. The elements in a list are separated by commas and are enclosed by a pair of brackets [ ].Creating a lists:A list is a sequence defined by the list class but also have alternative for creation of list without built-in function.Syntax: With Built-in function list( )list1 = list() # Create an empty listlist2 = list([2, 3, 4]) # Create a list with elements 2, 3, 4 list3 = list(["red", "green", "blue"])#Create a list with stringslist4 = list(range(3, 6)) # Create a list with elements 3, 4, 5list5 = list("abcd") # Create a list with characters a, b, c, dWithout Built-in Functionlist1 = [] #Empty list list2 = [2, 3, 4] #Integer type list list3 = ["red", "green"] #String type listlist4 = [2, "three", 4] #Mixed data type listExample: #Create listlist_1 = ["apple", "banana", "cherry"]#display listprint("Current List:",list_1)Accessing items from the list:An element in a list can be accessed through the index operator, using the following syntax: myList[index]. List indexes are starts from 0 to len(myList)-1.Negative indexing means beginning from the end,?-1?refers to the last item,?-2?refers to the second last item etc.Example:myList = ["The", "earth", "revolves", "around", "sun"]print("Postive index:",myList[4])print("Negative index:",myList[-2])Output:>>> %Run task1.pyPostive index: sunNegative index: aroundList Slicing [start : end]:The index operator allows to select an element at the specified index. The slicing operator returns a slice of the list using the syntax list[start : end]. The slice is a sublist from index start to index end – 1.Example:list1= [1,2,4,5,6,7,8]print("Slicing 2 to 5 index:",list1[2:5])print("Slicing before 3rd index value:",list1[:3])print("Slicing after 3rd index value:",list1[3:])Output:>>> %Run task2.pySlicing 2 to 5 index: [4, 5, 6]Slicing before 3rd index value: [1, 2, 4]Slicing after 3rd index value: [5, 6, 7, 8]Modifying Elements in a List:The syntax for modifying an element is similar to the syntax for accessing an element in a list.Example:#Create a listmotorcycles = ['honda', 'yamaha', 'suzuki']print(motorcycles)#Modify list through indexesmotorcycles[0] = 'Swift'print(motorcycles)Output:>>> %Run task3.py['honda', 'yamaha', 'suzuki']['Swift', 'yamaha', 'suzuki']List Methods for Adding , Changing and Removing items:Python has a set of built-in methods that you can use on lists/arrays.MethodDescriptionappend( )Adds an element at the end of the listcopy( )Returns a copy of the listcount( )Returns the number of elements with the specified valueindex( )Returns the index of the first element with the specified valueinsert( )Adds an element at the specified positionpop( )Removes the element at the specified positionremove( )Removes the first item with the specified valuereverse( )Reverses the order of the listsort( )Sorts the listEXERCISEPoint out the errors, if any, in the following Python programs.CodeDef max_list( list ): max = list[ 0 ] for a is in list: elif a > max: max = a return maxprint(max_list[1, 2, -8, 0])Output2. Codemotorcycles = {'honda', 'yamaha', 'suzuki'}print(motorcycles)del motorcycles(0)print(motorcycles) Output:3. CodeDef dupe_v1(x): y = [] for i in x: if i not in y: y(append(i)) return ya = [1,2,3,4,3,2,1]print aprint dupe_v1(a) Output:What will be the output of the following programs:Codelist1= [1,2,4,5,6,7,8]print("Negative Slicing:",list1[-4:-1])x = [1, 2, 3, 4, 5, 6, 7, 8, 9]print("Odd number:", x[::2])OutputCodedef multiply_list(elements): t = 1 for x in elements: t*= x return tprint(multiply_list([1,2,9])) OutputCodedef add(x,lst=[] ): if x not in lst: lst.append(x) return lstdef main(): list1 = add(2) print(list1) list2 = add(3, [11, 12, 13, 14]) print(list2)main() OutputC. Write Python programs for the following:1. Write a program that store the names of a few of your friends in a list called ‘names’. Print each person’s name by accessing each element in the list, one at a time. 2. Write a program that make a list that includes at least four people you’d like to invite to dinner. Then use your list to print a message to each person, inviting them to dinner. But one of your guest can’t make the dinner, so you need to send out a new set of invitations. Delete that person on your list, use del statement and add one more person at the same specified index, use the?insert( )?method. Resend the invitation.3. Write a program that take list = [30, 1, 2, 1, 0], what is the list after applying each of the following statements? Assume that each line of code is independent.list.append(40)list.remove(1)list.pop(1)list.pop()list.sort()list.reverse()4. Write a program to define a function called ‘printsquare’ with no parameter, take first 7 integer values and compute their square and stored all square values in the list. ................
................
In order to avoid copyright disputes, this page is only a partial summary.
To fulfill the demand for quickly locating and searching documents.
It is intelligent file search solution for home and business.
Related download
- edexcel gcse in computer science lesson activities for
- chapter 1 scalar variables and data types
- cody robson university of wisconsin madison
- ocr gcse 9 1 computer science j277 guide to
- objective pk
- list ends tamalpais union high school district overview
- juniata college
- python class room diary be easy in my python class
Related searches
- objective of financial management
- objective of finance manager
- finance manager objective statement
- finance manager resume objective examples
- objective for direct care worker
- financial resume objective examples
- finance manager resume objective examp
- resume objective financial industry
- objective for financial services resume
- well written objective for resume
- primary objective of financial managers
- best wording for objective on resume