LIST DEFINITION A list is an ordered set of values, where each value is identified by an index. The values that make up a list are called its elements. Lists and strings and other things that behave like ordered sets are called sequences. Updating in the existing list is possible.
ACCESSING ELEMENTS IN LIST >>>LIST2=[1,2,3,4,5] >>> print (LIST2[0]) 1 >>> print(LIST2[-1]) 5 >>>WORDS=[“hello”, “ hai ”] >>>print (WORDS[1]) hai
UPDATING IN A LIST In list you can add the element using the method append() list.append ( obj ) Example >>> list2=[1,2,3,4,5] >>> list2.append(9) >>>print (list2[]) [1,2,3,4,5,9]
Delete list elements To remove a element in a list, you can use either del statement if you exactly know which elements you are deleting or remove() method if you don’t know. Example >>>numbers=[17, 123,54,78,99,45,67] >>> del list[2] >>>print(numbers[]) [17, 123,78,99,45,67] >>> numbers.remove (123) >>>print(numbers[]) [17,78,99,45,67]
List operations Lists respond to the + and * operators much like strings; they mean concatenation and repetition here too, except that the result is a new list, not a string.
BASIC LIST OPERATIONS PYTHON EXXPRESSION RESULTS DESCRIPTION Len([1,2,3]) 3 length [1,2,3]+[4,5] [1,2,3,4,5] concatenation [‘hi’]*2 [‘hi’ ‘hi’] repetition in [1,2,3], 5 not in [1,2,4] True True Membership for x in [1,2,3,4,5] Print(x) 1 2 3 4 5 iteration
List slices A subsequence of a sequence is called a slice and the operation that extracts a subsequence is called slicing. Like with indexing, we use square brackets ([ ]) as the slice operator , but instead of one integer value inside we have two, separated by a colon (:)
List .append() append(x) method is used to add an item to the end of a list. Example >>>Veggies=[‘ carrot’,’cabbage’,’beetroot’,’beans ’] >>> Veggies.append (potato) >>>Print(veggies[]) [‘ carrot’,’cabbage’,’beetroot’,’beans’,’potato ’]
List.insert () The list.insert ( i,x ) method takes two arguments, with i being the index position you would like to add an item to, and x being the item itself. Example >>>Veggies=[‘ carrot’,’cabbage’,’beetroot’,’beans ’] >>> veggies.insert (3,’brinjal’) >>>print(veggies[]) [‘ carrot’,’cabbage’,’beetroot’,’brinjal’,’beans ’]
List.extend () T he list.extend (L) method, which takes in a second list as its argument. Example >>>fruits=[‘ apple’,’orange’,’grapes ’] >>> veggies.extend (fruits) >>>print(veggies[]) [‘ carrot’,’cabbage’,’beetroot’,’beans’,‘apple ’, ’ orange’,’grapes ’]
List.remove () To remove an item from a list remove(x) method which removes the first item in a list whose value is equivalent to x Example >>>Veggies=[‘ carrot’,’cabbage’,’beetroot’,’beans ’] >>> veggies.remove (‘cabbage’) >>>print(veggies[]) [‘ carrot’,’beetroot’,’beans ’]
List.pop() The list.pop([ i ]) method to return the item at the given index position from the list and then remove that item. >>>Veggies=[‘ carrot’,’cabbage’,’beetroot’,’beans ’] >>>print(veggies.pop(2)) >>>print(veggies[]) [‘ carrot’,’cabbage’,’beans ’]
list.index () lists start to get long, it becomes more difficult for us to count out our items to determine at what index position a certain value is located . >>>Veggies=[‘ carrot’,’cabbage’,’beetroot’,’beans ’] >>> print( veggies.index (‘beans’)) 3
list.copy () If working with a list and may want to manipulate it in multiple ways while still having the original list available to us unchanged, we can use list.copy () to make a copy of the list. >>>items= veggies.copy () >>>print(items[]) [‘ carrot’,’cabbage’,’beetroot’,’beans ’]
list.reverse () R everse the order of items in a list by using the list.reverse () method. >>> veggies.reverse () >>>print(veggies[]) [‘ beans’,’beetroot’,’cabbage’,’carrot ’]
list.count () The list.count (x) method will return the number of times the value x occurs within a specified list. >>>print( veggies.count ()) 4
List.sort () The list.sort () method to sort the items in a list. >>>list=[5,6,3,9,1] >>> list.sort () >>>print(list[]) [1,3,5,6,9]
List.clear () To remove all values contained in it by using the list.clear () method. >>> veggies.clear () >>>print(veggies[]) []
List range >>>range(1,5) [1, 2, 3, 4] >>> range(1,10,2) [1, 3, 5, 7, 9]
List Loop 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. Tour=[‘ chennai’,’mumbai’,’banglore’,’australia ’] for t in tour print(t)
Example Tour=[‘ chennai’,’mumbai’,’banglore’,’australia ’] for t in tour print(t) output: chennai mumbai banglore australia
Lists are mutab l e lists are mutable, which means we can change their elements.
Example
List Deletion
ALIASING if we assign one variable to another, both variables refer to the same object. >>>a=[13,14,6,8,9] >>>b=a >>>a is b true
CLONING LISTS 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.
List parameters Passing a list as an argument actually passes a reference to the list, not a copy of the list. Example: def double ( a_list ):
Tuples A tuple is a sequence of immutable Python objects. Tuples are sequences, just like lists. Examples tup1 = ('physics', 'chemistry', 1997, 2000) tup2 = (1, 2, 3, 4, 5 ) tup3 = ("a", "b", "c", "d“)
Accessing Values in Tuples To access values in tuple , use the square brackets for slicing along with the index or indices to obtain value available at that index. Example >>>tup1 = ('physics', 'chemistry', 1997, 2000) >>> tup2 = (1, 2, 3, 4, 5, 6, 7 ) >>>print ("tup1[0]: ", tup1[0] ) #for positive indexing >>>print ("tup2[1:5]: ", tup2[1:5]) # for slicing Output: tup1[0]: physics tup2[1:5]: [2, 3, 4, 5]
Updating Tuples Tuples are immutable which means you cannot update or change the values of tuple elements. But it can be able to take portions of existing tuples to create new tuples as the following example demonstrates
>>>tup1 = (12, 34.56); >>>tup2 = (' abc ', 'xyz'); # Following action is not valid for tuples tup1[0] = 100; # So let's create a new tuple as follows >>>tup3 = tup1 + tup2; >>>print (tup3) Output: (12, 34.56, ' abc ', 'xyz')
Delete Tuple Elements Removing individual tuple elements is not possible. Example: tup = ('physics', 'chemistry', 1997, 2000) print ( tup ) del ( tup ) print ("After deleting tup : " print tup ) Output: ('physics', 'chemistry', 1997, 2000) After deleting tup : Traceback (most recent call last): File "test.py", line 9, in <module> print ( tup ); NameError : name ' tup ' is not defined
Python Tuple Methods Python Tuple Method count( x ) -Return the number of items that is equal to x index( x ) -Return index of first item that is equal to x
Built-in Tuple Functions cmp (tuple1, tuple2) -Compares elements of both tuples . len ( tuple ) -Gives the total length of the tuple . max( tuple ) -Returns item from the tuple with max value. min( tuple ) -Returns item from the tuple with min value. tuple ( seq ) -Converts a list into tuple
Tuple Membership Test my_tuple = (' a','p','p','l','e ',) # In operation # Output: True print('a' in my_tuple ) # Output: False print('b' in my_tuple ) # Not in operation # Output: True print('g' not in my_tuple )
Comparing tuples The comparison operators work with tuples and other sequences. Python starts by comparing the first element from each sequence.
Decorate A sequence by building a list of tuples with one or more sort keys preceding the elements from the sequence
Undecorate By extracting the sorted elements of the sequence.
TUPLES AS RETURN VALUES a function can only return one value, but if the value is a tuple , the effect is the same as returning multiple values.
Example
DICTIONARIES
Definition for dictionaries Python dictionary is an unordered collection of items. While other compound data types have only value as an element, a dictionary has a key: value pair. Dictionaries are enclosed by curly braces ({ }) and values can be assigned and accessed using square braces ([]).
# empty dictionary my_dict = {} # dictionary with integer keys my_dict = {1: 'apple', 2: 'ball'} # dictionary with mixed keys my_dict = {'name': 'John', 1: [2, 4, 3]} # using dict () my_dict = dict ({1:'apple', 2:'ball'}) # from sequence having each item as a pair my_dict = dict ([(1,'apple'), (2,'ball')])
A ccess elements from a dictionary my_dict = {' name':'Jack ', 'age': 26} # Output: Jack print( my_dict ['name']) # Output: 26 print(my_dict.get('age'))
change or add elements in a dictionary my_dict = {' name':'Jack ', 'age': 26} # update value my_dict ['age'] = 27 #Output: {'age': 27, 'name': 'Jack'} print( my_dict ) # add item my_dict ['address'] = 'Downtown' # Output: {'address': 'Downtown', 'age': 27, 'name': 'Jack'} print( my_dict )
delete or remove elements from a dictionary Either remove individual dictionary elements or clear the entire contents of a dictionary. You can also delete entire dictionary in a single operation. To explicitly remove an entire dictionary, just use the del statement.
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'} del dict ['Name']; # remove entry with key 'Name' dict.clear (); # remove all entries in dict del dict ; # delete entire dictionary print " dict ['Age']: ", dict ['Age'] print " dict ['School']: ", dict ['School']