You are on page 1of 21
—_—— UNIT IV LIST, TUPLES, DICTIONARIES ea 4. LISTS The list is a most versatile data type available in Python which can be written as alist of comma-separated values (items) between square brackets. Important thing about a list is that items in a list need not be of the same type. Python offers a range of compound datatypes often referred to as sequences. List is one of the most frequently used and very versatile datatype used in Python. Python has a great built-in list type named "list". List literals are written within square brackets [ ]. Lists work similarly to strings -- use the len () function and square brackets [ ] to access data, with the first element at index 0. The list type is a container that holds a number of other objects, in a given order. The list type implements the sequence protocol, and also allows you to add and remove objects from the sequence. Example Empty List >>> list=[] >>> list u Integer List >>> list]=[1,2,3] >>> list] (1, 2, 3] List with mixed data types >>> List2=[10,25.5,'prema’] >>> list2 [10, 25.5, ‘prema'] Nested List >>> list4=["selvi",[10,20,30],'prema’] ee sts 4.2 List, Tuples, Dictionaries _ io ala >>> list4 ['selvi', [10, 20, 30], ‘prema’] Accessing List elements User can use the index operator [] to access an item in a list. Index starts fo So, a list having 5 elements will have index from 0 to 4. will raise an IndexError. The iad Trying to access an element other that this must be an integer. We can’t use float or other types, this will result into TypeError, Example >>> list=[10,20,30,40,50] >>> print(list[0]) 10 : >>> print(list[3]) 40 >>> list=['a’, BY, 'c', 'd'] >>> list[3] ‘a’ >>> list=[Tamil, ‘Kavi’, 'Duraisamy'] >>> print(list[2]) Duraisamy >>> list4=["Kavitha" [10,20,30 i >>> list4[0] oe "Kavitha’ >>> list4[0][0] "KI >>> list4[1][0] 10 >>> list4[2][0] —T \ Problem Solving and Python Programming 4.3 4.1.1. List operators Lists respond to the + and * }) Concatenation Concatenation operator is used to list. Operator used for concatenation is Plus (+) operator. Example >>> list1=[10,20,30,40,50] >| >>> list3=[Tamil’, 'kavi' duraisamy'] >>> list] Hist2 [10, 20, 30, 40, 50, ‘a’, b’, 'c'] >>> list] +list2Hist3 [10, 20, 30, 40, 50, 'a', 'b', 'c', ‘Tamil’, 'kavi', 'duraisamy’] ii. Repetition ©Perators much like strings; they mean pt that the result is a new list, not a string. namely concatenation (A), repetition (*). Join or concatenate elements of two or more Repetition operator is used to repeat the list for given number of times. Operator used for repetition is asterisk (*) operator. Example >>>listl=[10, 20, 30, 40, 50] >>> list2=['a',''e'] >>> list3=[ Tamil, 'kavi' duraisamy'] >>> listl*2 [10, 20, 30, 40, 50, 10, 20, 30, 40, 50] >>> List2*3 [a','D,‘c','a', bY, 'c,'a' "BS 'e') 4.1.2. List slices User can access a range of items in a li A subsequence of a sequence is called a sl subsequence is called slicing. Like with indexing, st by using the slicing operator colon (:). lice and the operation that extracts a we use square brackets C }) as the we have two, separated by a one integer value inside 1 User can access 4 part of complete i of the lists. Syntax f the list to be sliced. ‘End’ indicates end of from the last. ‘start’ indicates starting index 0! nt to be sliced. Negative in list eleme dex takes values Example >>> list={10,20,30,40,50,60,70] >>> list[0:5] [10, 20, 30, 40, 50] >>> list[2:6] [30, 40, 50, 60] >>> list[:3] [10, 20, 30] >>> list{1:] [20, 30, 40, 50, 60, 70] >>> list{:] [10, 20, 30, 40, 50, 60, 70] >>> list[:-5] [10, 20] >>> list[-2:] 60, 70] 4.1.3. List Methods Methods that are available with list object in Python programming t ar ible with 11 ject i ing are tabule® below. The: . They are Baise accessed as list.method(). Si . Some of the methods have already bet Problem Solving and Python Program puilt-in Functions Method Purpose Example >>> list=[10,20,30,40,50] en(list) Returns the length of the list >>> len(list) 5 >>> list=[10,20,30,40,50] >>> min(list) 10 >>> max(list) 50 >>> list=[10,20,30,40,50] >>> max(list) 50 Returns the minimum value of the list min(list) Returns the maximum value of the list max(list) Various list methods are given below i. append() The method list.append(x) will add an item (x) to the end of a list. Appends object obj to list. Example >>> list=[10,20,30] >>> list.append(40) >>> list [10, 20, 30, 40} ii insert() Insert an item at the specified index. The list.insert(i,x) method takes two “rguments, with i being the index position you would like to add an item to, and x being the item itself. Example >>> list >>> list.insert(1,'l >>> list ['a', "bi, 'e', 'd', 'e'] | | 406 List, Tuples, Dictionaries ‘ount(x) method will return the number of times the va A ie the count of number of items passeq aan. within a specified list. Return an ty, Example >> list=[1,1,2,3,4,'a'/2'/b' tamil] >>> list.count(1) 2 >>> list.count('tamil!) 1 iv, extend() If user want to ¢ ‘ombine more than one Iii ist, then user can use the Tistong method, which takes in 4 second list as its argument. Add all elements of g ling another list, Example sisamy’Sivalingam amma’ >>> list] extend(tist2) >>> list] Ctamit, ‘kay ‘, ‘duraisamy', V. index() 1 | We can use list.index(x), whe* » to return the index int value, tc he list where that item is oe 0 one item with Value x, this Method will ret mn the first index lo Example >>> Tist=[i 12453, 01 35 3 *>> list.index(t}) el 0 Problent 8 hon Prnancannnetie >>> list.index(7) ValueError: 7 is not in list ‘i remove() Method used to remove an element from the li from a list, remove(x) method which removes the f |. When user need to remove an item in a list whose value is jem aquivalent to x can be used. Example >>> list=['cse''ece','eee' eie',' >>> list.remove('eie') >>> list [ese’, 'ece’, ‘eee’, 'civil’] vii pop() Method used to remove and returns an element removed from the list, User can use the list.pop([i]) method to return the item at the given index position from the list and then remove that item. Example >>> list=[ese’,'ece'cee','eie','ci >>> list.pop(3) 'eie’ >>> list ['cse, 'ece’, ‘eee’, ‘civil’] Mil revers ce y list. User can revet e the order rder of items in the thod. Perha alphabetical order. a Method used to reverse the 0} ots ina list by using the list.reverse() method ‘Se reverse alphabetical order rather than traditi it is more convenient for us ional wee] reverse() 7 So ist-10''29 >>> list. >>> list te fa 2's BT >>> tist2=[10,20,30,40] >>> ist2.reverse() >>> list2 [40, 30, 20, 10) ix. sort! ; ae : e aia used to sort items in a list in ascending orde: method to sort the items ina list. r. User can use the list.s¢ Example >>> list=['b'z'2',c'se'] >>> list.sort() >>> list ['a', bt, 'e','e', '2'] >>> list2=[20,40,10,50,30] >>> list2.sortQ) >>> list2 [10, 20, 30, 40, 50] x. clear() User can remove all values contained in it by using the list.clear() met Method used to clear or remove all the elements in the list. Example >>> list=[20,40,10,50,30] >>> list 20, 40, 10, 50, 30] >>> list.clear() >>> list u Problem Solving and Python Programming 4.9 xi,copy() Method used to copy elements of the list. When user working with a list and may want to manipulate it in multiple ways while still having the original list available tous unchanged, user can use list.copy() to make a copy of the list. Example >>> list=['tamil,'kavi’,'selva',durai’] >>> new=list.copy() >>> new ['tamil’, 'kavi', 'selva', 'durai'] 4.1.4 List Loop User use a loop to access all the elements in a list. A loop is a block of code that repeats itself until it runs out of items to work with, or until a certain condition is met. In this case, our loop will run once for every item in our list. With a list that is three items long, our loop will run three times, Using a “for” loop user can iterate though each item ina list. It has the ability to iterate over the items of any sequence, such as a list or a string. Syntax for iterating_var in sequence: statements(s) Ifa sequence contains an expression list, it is evaluated first. Then, the first item in the sequence is assigned to the iterating variable ifterating_var. Next, the statements block is executed. Each item in the list is assigned to iterating_var, and the statement(s) block is executed until the entire sequence is exhausted. Flowchart Example for iterating_var in True Body of the loop If no more item in Zi Next statement >>> for fruit in [apple’banana’,'mango’]: print("l like" fruit) Ilike apple like banana Tlike mango S55 mylist = [11,2,3)14,5,6,7118,9,10]] >>> for x in mylist: if len(x)=3: print x [1, 2, 3] [8, 9, 10] colors=['Red','Blue','Green’,"Yellow’ "Pink'] for a in colors: ; print(a) Red Blue hes ea | Problem Solving and Python Programming 4.11 OE TEaearree Green ] Yellow j Pink i be 4s List Mutability Lists are mutable, Which means user can change their elements. Using the packet operator on the leff side of an assignment, user can update one of the elements. Example >>> list=['red' blue’ green’ white] >>> list | [red blue’ ‘green’, Swhite’] >>> list{3]=black’ >>> list [red’, ‘blue’, 'green’, black] The bracket operator applied to a list can appear anywhere in an ex-pression. When it appears on the left side of an assignment, it changes one of the elements in the list, so the first element of list has been changed from ‘white’ to ‘black’. An assignment tan element of a list is called item assignment. Item assignment does not work for stings, Example >>> sr TEST >>> str "TEST’ >>> stf2JE"X" Traceback (most recent call last): File "", line 1, in TypeEror: str’ object does not support item assignment ——E cy Tuples, Dictionaries = 4.12 us TO ral elements at Once: ' vel with the slice operator We can update se >> ef] <— pp>a [a,b "0, ds ‘f] p> af (2) >>>a [tai x's'd's'e' Ty ‘User can also remove elements from a list by assigning the empty list to them: >a ai, 'x','d,'e' "fl >>> af 3L pp>a [a','a'e', ‘FI Mutable list allows users to delete list element using del keyword ) S55 name=[tamil/selva’ Kavi] >>>name [tamil ‘selva’, kavi'] ) >>> del name[1] >>> name (tamil, ‘kavi'] 4.1.6. List Aliasing Alias name is used to indicate that a named list is also known or more fami under another specified name. Since variables j i ign 0 . . refer to objects, if user assig? variable to another, both variables refer to the same object. 7 Example >>> a=[10,20,30] >>> b=a >>>b 4 a {10, 20, 30] >>>aisb True es indicate the sam Both cae Seer Te list. Changes made to the list with one name are also refleote p Provide two different names given to one list. example >>> a [10, 20, 30] >>> bll]-25 >>>a [10, 25, 30] 4.1.7 Cloning List If we want to modify a list and also keep a copy of the original, we need to be able to make a copy of the list itself, not just the reference. This process is sometimes called cloning, to avoid the ambiguity of the word copy. Syntax new_list = old_list[:] The easiest way to clone a list is to use the slice operator: >>> list=[10,20,30] >>> new=list[:] >>> new [10, 20, 30] Taking any slice of a creates a new list. In this case the slice happens to consist of the whole list. Changes made in new list will not reflect in old list as like in alias. Now Weare free to make changes to new without worrying about old list. Example >>> new[2]=25 >>> new [10, 20, 25] >>> list [10, 20, 30] 4.14 List, Tuples, Dictionaries 4.1.8. List Parameters Passing a list as an argument act the list, Since lists are mutable changes mi well. ‘tually passes a reference to the list, not g oy ade to the parameter change the arng some. list = ["some", "values", "in", "a", "list", ] func(*some_list) This is equivalent to: funo("some", "values", "in", "a", "list") The fixed x param might warrant a thought: func(5, *some_list) funo(5, "some", "Values", "in", "a", "list") 4.2. TUPLES A tuple is a sequence of values like a list. The values stored in a tuple can b type, and they are indexed by integers. A tuple is a sequence of immutable P! objects. The important difference between list and tuple is that tuples are immutabl the values of tuples cannot be changed but values of list can be updated. Tuple parentheses “()”, oe Creating a tuple is as simple as putting different comma-separated - eee ed = He — comma-separated values between parentheses also. P fate 2 Pp ' iple assignment feature that allows a tuple of variables 07 th {gnment to be assigned values from a tuple on the right of the assignmet- Example >>> tup=(10,20,30) >>> print(tup) Problem Solving and Python Programming 4.15 (10, 20, 30) === >>> tup2=(‘a!,'b!,'c!) >>> tup2 (a', 'b’, 'c') | >>> tup3=("tamil"," >>> tup3 | Ctamit’, 'selvan’, tkayiry >>> tup4=(10,20.5,'a', Selvan' vi") tamil") >>> tup4 (10, 20.5, ‘a’, 'tamil') 42.1. Tuples are immutable Values of tuples cannot be chan; of ist can be changed or updated. Hen will generate an error message, ged or updated, List are mutable, that is values ce tuples are immutable. If user try to modify, it ; | Example >>>tup=(10,20,30,40,50) ; >>>tup (10,20,30,40,50) >>> tup[1]515 Traceback (most recent call last): File "", line 1, in TypeError: 'tuple' object does not support item assignment 42.2 Tuple Assignment Python has a very powerful tuple assignment feature that allows a tuple of Variables on the left of an assignment to be assigned values from a tuple on the right of theassignment, Sample >>> x,y=10,20 print(x,y) 1020 ) ValucError: not enough values to unpack (expected 3, got 2) >>> x,Y=10,20,30 ValucError: too many values to unpack (expected 2) Tuple assignment is often useful to swap the values of two variables. Example >>> x=10;y=20 >>> print(x,y) 1020 >>> temp=x >>> x=y >>> y=temp >>> print(x,y) 2010 Tuple assignment is more elegant to swap two values. Example >>> x,y=10,20 >>> print(x,y) 1020 >>> X%Y=y,x >>> print(x,y) 2010 4.2.3. Basic Tuples Operations i, Concatenation Two or more tuples can be concatenated or joined using concatenation opel @). >> t1=(10,20.5,30) 'a’,'b’,'c') >>> 13=(‘tamil’,'kavi') o> thtt24t3 (10, 20.5, 30, 'a’, "b', " c!, "tamil, 'kavi') ii Repetition Values of tuples can be repeated for specified number of times. User can repeat the object of the tuple using * operator, Example >>> tl=(10,20.5. .'a','b', tamil’) >>> tl *2 (10, 20.5, 'a', "b', 'tamil', 10, 20.5, ' >>> t2=(1,2,3) >>> t2*3 , 2, 3, 1, 2, 3, 1, 2, 3) a', 'b', "tamil" iii, Membership The membership Operator in returns True, retums False. Membership operator is used to ch tuple or not. if the element is in the tuple else it eck whether given element is in the Example >>> t1=(10,20,30,40,50) >>> print(10 in tl) True >>> print(6 in t1) False *. Tuple Indexing User can use the index operator [] to access an item in a tuple where the index “S'S ffom 0. So, a tuple having 6 elements will have index from 0 to 5. Trying to Tuples, Dictionaries an clement other that (6, 7 integer, Example >>> tuple= (tain i) >>> print(tuple[0]) t >>> print(tuple[3]) I © an IndexError, ‘The index D We cannot use Moat or other types, This will result into Typ Niu elrroy, | P$ $$$ Python tuples allows negative indexing for its sequence, The index Of -1 refers ig last item, -2 to the second last item and so on, Example >>> tuple=(U aim) >>> print(tuple[-1]) 1 >>> print(tuple[-3]) M v. Tuple Slicing User can access a Tange of items in a tup! le by using the slicing operator. Slic operator in python language is colon(:). Example >>> tuple=(ty am) >>> print(tuple[0:3) (ty aly 'm') >>> print(tuple[2:3)) (m') 4 >>> print(tuple[2:]) (mt, 1) >>> print(tuple[:]) (ta, my, 1) >>> print(tuplef:-2}) eI olvings and Python Pray anti, AND i. Deleting Tuple User cannot change the elements jn remove items from a tuple, But deleting del. 4 tuple, Likewise uncr cannot delete or «ple entirely is possible wing, the keyword pxample >>> print(t) (10, 20, 30) >>> del t >>> print(t) NameError: name 't' is not defined vii. Comparing Tuples The comparison operators work with tuples and other sequences; Python starts by comparing the first clement from cach sequence. If they are equal, it goes on to the next element, and so on, until it finds elements that differ. Example 555 11=(10,20,30) >>> t2=(5,15,25) >>> tl>t2 True >>> tl list=[10,20,30] ee tup=(10,20,30) >>> print(list) >> prit print(tup) [10, 20, 30] (10, 20, 30) >>> list{1]=40 >>> tup[1]=40 >>> print(list) [10, 40, 30] TypeError: ‘tuple’ object does not Support item assignment

You might also like