Download as pdf
Download as pdf
You are on page 1of 11
{A Introducing Lists ‘A What ore Python Lists @ 4.1 INTRODUCTION Till now you have enjoyed writing simp i is i a 'ple Programs in Python. This session will enhance your Python knowledge little more by talking about a useful datatype of Python called Lists. Lists are used to represent, use and manipulate a sequence of values in multiple ways and this session will talk about the same. 4.2 INTRODUCING LISTS Before we talk about the Python lists, let us first perform an activity. AA, ~~ Activity [A | PREPARE A SHOPPING LIST os oy Prepare a shopping list after consulting your mother. Say your shopping list looks somewhat like : 7 tell hoy pany items are theme in the shopping list? That what he Now, can you we length of the shopping list ? —8 itews___—_——_ = 236 ARTIFICIAL INTELLIGENCE-K / 3. What are the first and last serial numbers of the shopping list items ? __1 (first) and 8 (last) 4 ‘What is the third item of the shopping __rice with serial number 3. 5. What is the serial number of the 6th item in the list ? list and what is its serial number ? _ ee 6. What are the first and last items of the shopping list ? __45¢ item milk__{with serial number 2) Last item onion_(with serial number 8) PB, saivin 1 1B SHOPPING LIST WITH A TWIST 2B Prepare shopping list like earlier but this time, start the item numbering from 0 onwards, i-e., as 0, 1, 2, ... instead of 1 onwards. 1. Shopping list this time would look like : Shopping List 0. milky 1. butter 2. rice 3. Cagy 4. juice S. bread 6. fruity 7. oniow 2. What is the length of the shopping list this time ? —8 tem, 3. What are the first and last serial numbers of the shopping list items ? —0 (first) amd 7 (Los 4, What i ird i is the third item of the shopping list and what is its serial number ? rice with serial n a Session 4 5. What is the serial number of the 6th item in the list 2 s. INTRODUCTION To Usts 237 6. What are the first and last items of the shopping list ? tt teen mile ( with serial number 0) Last ite onion. _( withe serial number 7)_ Can you see any difference between the two lists of above two activities ? Well'you are right. There is not much of a difference except that the second list begi numbering ofits items 0 onwards. Thus, for every item its position and serial number bose different. That is, For ist item , serial number is 2, For 3rd item, serial number is 2 ‘And so on. 4.3 WHAT ARE PYTHON LISTS ? } ee Python lists are sequence of values somewhat like list of 2 ean muti Ee Bae on list is simply activity 18 above. In other words, a Python ist is simply elicah cf ealitetined a sequence of values stored in a specific order with each a specific order with each value identified by its index number in that order. The value identified by its index index numbers of Python lists start 0 onwards and go pipes ia aeroey like 0, 1, 2, ... 4.3.1 How to Create Python Lists ? To create Python lists, you can put a list of values with comma in between the items, enclosed in square brackets, e.g., >>> mylist = (2, 4, 6, 8, 18] It will create a list with five numbers Lists are created by enclosing and name it as mylist. comma-separated values inside You can display the list items by simply _| [B Python 3.79Shetl_ square typing its name on the prompt in the | Ble Est Shell Debug ptions Window Help interactive mode, e.g., (see figure) >>> mylist = [2, 4, 6, 8, 10] >>> mylist >>> mylist —*> [2, 4, 6, 8, 18) [2, 4, 6, 8, 10] >>> print (mylist) [2, 4, 6, 8, 10) You can also print the list by using the >>> list name with print() (see figure) — SS Session 4 INTRODUCTION TO Usts 237 5. What is the serial number of the 6th item in the list ? S. 6 What are the first and last items of the shopping list? tt ten mile ( with serial number O)_ Last item onion. _( with serial number 7)__ Can you see any difference between the two lists of above two activities ? Well, you are right. There is not much of a numbering of its items 0 onwards. Thus, for different. That is, For Ist item , serial number is @, difference except that the second list begins ‘every item its position and serial number become eneenaninttenaainaeinansiaaeenctmaamne For 3rd item, serial number is 2 ‘And so on. i 4.3. WHAT ARE PYTHON LISTS ? -_ Python lists are sequence of values somewhat like list of ean ssa ee aaah on list is simply a activity 1B above. In other words, a Python list is simply, gF¥thom lst simply a sequence of values stored in a specific order with each a specific order with och value identified by its index number in that order. The _value identified by its index index numbers of Python lists start 0 onwards and go Humber in that ordes. like 0, 1, 2, ... 4.3, How to Create Python Lists @ To create Python lists, you can put a list of values with comma in between the items, enclosed in square brackets, €.9., >>> mylist = [2, 4, 6, 8, 10] 4 ect fai 3 It will create a list with five number in aa ae) AOA and name it as mylist. comma-separated values inside You can display the list items by simply | [4 Python 37.9She square brackets, typing its name on the prompt in the | Ble _Edit_Shell Debug ptions Window Help _ interactive mode, e.g., (see figure) >>> mylist = (2, 4, 6, 8, 10) >>> mylist >>> mylist [2, 4, 6, 8, 10) easel >>> print (mylist) (2, 4, 6, 8, 10) © You can also print the list by using the | >>> list name with print() (see figure) ... 238 ARTIFICIAL INTELUGENCE-K ir i int-numbers, Python lists can store any type of values in them - integers, floating Po” strings, and even a combination of values, such as + >>> mylista = (2, "Rudy", 93-5+ va") >>> mylist] [2, 'Rudy', 93.5, 'A') >> If you use the type( ) with type as list : list name, Python will show its Ld Python 3.7.9 Shell >> >>> type (mylist) >> “The type() function when used with a list name 4.3.2. Checking the Length (Number of Items) of the List The length or the size of a list means the number of items in the list. To check the length (number of items in the list), you can use the len( ) function with list name as : [d Python 3.7.9 Shell Ble Est Shel Debug Options Window Hep wan >>> mylist 12, 4, 6, 8, 10) >>> len (mylist) 5 >>> mylistl [2, ‘Rudy’, 93-5, A‘) >>> len(mylisti) 4 ‘The len() function when used wit alist name gives its length, “e., no. of tems in the ist Refer figure 1 Note The len() function returns the size or length of the list, i.e., the number of elements in the list. 4.3.3. Accessing Individual Items of a List Python list’s items are intemally numbered as 0, 1, 2, 3...(Positive Indexes). That is, ‘the 4 item has the index number as @ | ‘the 2"! item has the index number as 1 ‘the 3" item has the index number as 2 The last item has index number as length-1 op size-1 1-1 or size~ Session 4 : INTRODUCTION TO Lists 239 python sequences such as lists have positive indexes as well as the negative indexes. ‘That is, ‘the last item has the index number as -1 the 2" last item has the index number as -2 the 3" last item has the index number as -3 The first item has index number as length or -size) Graphically, it can be depicted as : th = 5 ———_} ipl ed | eta] TN | tO" | Positive index for the first item in the list = 0 | Positive index for last item of a list = size -1 | Negative index for the first item in the list = -size Negative index for last item of a list = To access an element, just give its index (positive or negative, any) in the square brackets along with the list name, ie., as : [] For example, consider our lists mylist and mylist1 as created above : enn [& Python 3.7.9 Shell | Bie Est She Debug Options window Hep _ >>> mylist [2, 4, 6, 8, 10) >>> mylisti [2, "Rudy', 93-5, ‘a'l >>> Now to access the first items of mylist and mylist!, you can write mylist[OJand mylisti [0] because the index number of the first item is 0 (see below). 35> mylist {0}, mylisti(0] (2, 2) >>> 260 ARTIFICIAL INTELUGENCEX 4 the negative index for ‘You may also use the negative index forthe frst eit For my teem is 6 as the the fist item is -5 while for mytistt, the negative ve fo 5 and 4. lengths of mytist and mylist1 respectively are >>> mylist[-5] (2, 2) >> 4.3.4 Accessing all Items of a List fe To access all items of a list one by one, you can use a for statement of Python, which picks To access Mery om a sequence anit ou se tem a ou want JER used as: for in < ‘listname>: using as individual For example, consider the list mylist containing item 25 [2, 4, 6 8 you need to write : statement with it to print individual items, for oneitem in mylist = print (oneiter) It will print the items of the mentioned list (mylist) one by one as = iten 10]. If you use for Before we proceed to more examples, you need to know about the following important things about the for statement (also called for loop of sequences) : © The used with for loop must be a legal identifier. «© There must be a colon at the end the for statement’ first line (the header line of for loop)- © The lines below the header line of for loop, which are using the must be indented inwards. es Jv It must be a legal identifier and it will access Following figure explains it : gas individual elements of the list one by one The code lines using the open lemons of i for oneiten in aylist 7 Should be a valid ist ana must Pe, Tincand ~~, Print (oneitem) be crested betine here all be at th should all be at the print("__") It must be at the end of header line of for loop same indent level Session 4: INTRODUCTION TO usts 241 Let us use the for loop for another list mylist1 and understand how it works : item in mylistl = =, item) © print ("#..- + ' # t 4.3.5 Modifying an Item in the List To modify an item in a list, just assign the new value to its accessing name, i.e., [ ] = For example, to change the 3rd item of mylisti to 95.5, you may write : >>> mylistl [2, tRudy', 93-5) 1311 355 mylisei [2] = 95-5 d>> mylist2 (2, ‘Rudy', 98.5, 'A'T mylistt [2] = 95-5 Note Changing the value of an it variable, i.e., assign a new val fem in a list is the same as changing the value of @ ue to item's accessing name. 4.3.6 Adding an tem in the List | To add an item to a list, use append( .append() | ror example, to add element 12 to ist mylist [2, 4, 6, 8, 10], you may write = >>> mylist: 4, 6, 10) mylist append (12) mylist-append(12) CZheck Point Sn 1. The function to check the type of a list is = (@ append( ) © type). % (© length( ) (@) len) 2. The function to check the size of a list is : @ append( ) © type() (©) length( ) @ let | 3. The index of the first item in a list is__ @o @1 (© size @ -size a iiiictct. 2H2_ ARTIFICIAL INTELUGENCE-Wx 4, The index of the last item itv a list is (@0 (b) 1 oe il) entre oa 7 (0) size (a) onl 5, The statement that can be used to access all items ‘of a list one by one I* (a) all () items (0 for Gee 6. The function to add new item to @ list is @ append) () type() (© length) (Wd) ten) < Let Us REVISE «© APython list is simply a sequence of values stored in a specific order with each value identified by its index number in that order. 4 The len(listname>) function returns the size or length of the list , list. Positive index for the first item in the list is 0. Positive index for last item of a list is stze-1. Negative index for the first item in the list is ~slze ‘Negative index for last item of a list is ~1. 4. Using a for loop all items from a list can be ‘accessed one by one, Using append(), a new item is added to a list Splution Time ion Ting 1. Take this list of items animals « ['cat", ‘dog’, ‘mouse’, ‘hamster’ the number of elements in the ‘wa7>w print out each item in the lst using a for loop Ans. ‘animals = [‘cat", ‘dog’, ‘mouse’, ‘hamster’ ] for one in animals : print (one) pop annals © ['cat's "dop', ‘@ouse's ‘hamater’) Sop for one ip animals t print (one) cat dog mouse hamster 2. Print the firstanimal in the animals list Ans. print (animals [0]) ——— Session 4 : INTRODUCTION TO Lists 243. +3. Print the first animal in the animals list (without using the index 0). Ans size = len(animals) print(animals[ -size]) 4, Print the last animal in the animals list. Ans. print (enimals[-1]) Print the last animal in the animals list (without using the index —1). Ans. size = len(animals) print (animals[size-1]) 6. Add animal “python” to the list of animals Ans. animals .append(“python”) 7. Change the last element of the animals list (after adding python) to “rabbit”. Ans. Size = len(animals) aninals[size-1] = "rabbit" 8. There is an error in the answer of the previous question. Find the error and correct it. ‘Ans. The variable size used in the 2nd line of code does not exist, hence it will give error. Variable Size exists (S capital) not size, thus by changing size to size, we get the desired result : Size = len(animals) animals[Size-1] = "rabbit" 9. Correct the error in the given code. for name in [‘Isha', 'Misha', ‘Trisha']: print(name, len(name)) Ans. There is wrong indentation in the given code. The second line of the code is part of for loop used for a list, hence it must be idented below it. The corrected code will be : for name in ["Isha', ‘Misha’, Trisha’): print(name, len(name) ) 10. What will be the output produced by the corrected version of previous question, given that len( ) gives the number of characters in a string ? Ans. The output will be : Isha 4 Misha 5 Trisha 6 < GLOSSARY UUst_ A named sequence of items with items stored in a specific order with each value identified by i ‘umber in that order. its index a. | 4a>v ow 244 ARTIFICIAL INTELLIGENCE-IX Assignment — SeEenaneuene i. 12. 1B 14, Wat are lies tn Python he result of the following statement ? Consider list things = “clowns”, “snakes”], what will be # print(things[1]) Why did the above code print “snakes” and no! What changes would you make in above code ( Write code to modify the 1st item of the list as “clowning”. What will be the output of the following code ? “clowns” ? (Q. 2) 40 that “snakes” gets printed 7 things = ["clowns", “snakes"] print(things) ‘things[1] = "bats" print (things) Write code to add “spiders” to the list things used above, What will be the output of the following code ? things = ["clowns", "snakes", "spiders"] print(things) things[1] = "bats" things. append("beetles") print (things) PRACTICAL ASSIGNMENT Create a list namely test having at least 3 integers, 2 floating point numbers and two strings. Print the first element from the list test. Print the last element from the list test. . Print the 2nd element from the list test. Print the 2nd last element from the list test, Print the 3rd element and the 3rd last element from the list test. ’. Print all elements from the list test. . Print the size of the list test now. . Add element “Ditto” to the list test. 10, Print the size of the list test now. Print the last element from the list test, Print the 2nd last element from the list test. Modify the 2nd last element of the list test as “new”, Print the size of the list test now, '

You might also like