430 likes | 450 Views
Datastructures in Python By – Tanmay Jain. Types of data structures. There two types of data structures: Built-in data structures, data structures that provided by default Eg: list, dictionary ,tuple…
E N D
Datastructures inPython By – Tanmay Jain
Types of datastructures • There two types of datastructures: • Built-in data structures, data structures that provided bydefault • Eg: list, dictionary,tuple… • User-defined data structures (classes in object oriented programming) that are designed for a particulartask • Eg: Stack ,Queue…
Python built in datastructures • Python has set of built in data structures: • lists • tuples • dictionaries • sets
Lists • An ordered collection ofitems • List items does not need to be of sametype • We can have numbers, strings , list etc in the samelist • Listnotation • A = [1,”This is a list”,‘c’,2.5] • B =[] • C =list()
Make a list usingstring • >>> lst = 'Welcome tomeetup'.split() • >>>lst • ['Welcome', 'to', 'meetup'] >>> lst ='What,a,wonderful,world'.split(',') >>>lst ['What', 'a', 'wonderful','world']
Access the items in thelist • >> names = [ ‘Rahul’, ‘Mahesh, ‘Aishwarya’] • Read one: • >> names[0] • >> Rahul • >>names[-1] • >>Aishwarya • Read one at a time: • >> for name innames: • printname • Rahul Mahesh Aishwarya
Methods ofLists • List.append(x) • – Adds an item to the end of thelist • Eg: • >> list_items = [1, 2, 3, 4,5] • >>list_items.append(6) • >>list_items • >> [ 1, 2, 3, 4, 5, 6]
List.extend(L) • - Extends the list by appending all the items in the given list ‘L’ to the existinglist • Eg: • >> list_items = [1, 2, 3, 4,5] • >> list_items.extend([6, 7, 8,9]) • >>list_items • >> [ 1, 2, 3, 4, 5, 6, 7, 8 , 9]
List.insert(i,x) • - Inserts an item x at indexi • Eg: • >> list_items = [1, 2, 3, 4,5] • >> list_items.insert(3,10) • >>list_items • >> [ 1, 2, 3, 10, 4,5]
List.remove(x) • - Removes the first occurrence of the item from the list whose value isx • Eg: • >> list_items = [1, 5, 3, 4, 5,5] • >>list_items.remove(5) • >>list_items • >> [ 1, 3, 4, 5,5]
List.pop(i) • - Remove and returns item at index i,default value of i is last index of thelistEg: • >> list_items = [1, 5, 3, 4, 5,8] • >> list_items.pop() • >> 8 • >>lst • >> [1, 5, 3, 4,5] • >>list_items.pop(2) • >> 3 • >>lst • [1, 5, 4, 5]
Some other methods ofLists >> a = [1, 2, 3, 4, 5, 6, 7,6] • a.count(x) • >>a.count(6) • >>2 • a.index(x) • >>a.index(6) • >>5 • a.reverse() # Returns occurrence of specifiedx # Returns the first index where the given valueappears # Reverses order of list • >>a.reverse() • >> [6, 7, 6, 5, 4, 3, 2,1] • a.sort() • >> a • >> [1, 2, 3, 4, 5, 6, 6,7]
Slicing aList • List[ start,stop] • >> lst = list(‘MontyPython’) • >> lst • >> ['M', 'o', 'n', 't', 'y', ' ', 'P', 'y', 't', 'h', 'o','n'] >> lst[6:10] >> ['P', 'y', 't','h'] >> lst[0 :5] >> ['M', 'o', 'n', 't','y']
>> lst[:5] >> ['M', 'o', 'n', 't','y'] >> lst[6:10] >> [''P', 'y', 't', 'h','o'] >> lst[5:] >> [' ', 'P', 'y', 't', 'h', 'o','n'] >> lst[-12 :-7] >> ['M', 'o', 'n', 't','y']
Practice • Write a program to read the input and processit • Input will be items separated by space. Perform the following actions. a). Make a list of the input provided and printit • Count the no of items in the list and printit • Ask the user to provide a item as input and find the index of the item , if the item is not present print ‘Item not found’ else print theindex. • Find the Occurrence of the item in thelist d). Reverse the list and printit • e). Sort the list in descending order and print the sorted list • Input: • Enter the numbers :a c d e z k mo
Dictionary • Consists of Key– Valuepair • Keys needs tounique • Items of the dictionary are notordered • Eg: • >> empty_dict =dict() • >>empty_dict • >>{} • >> phonebook = {'Rock': 999999999, 'Rashmi': 888888888, 'Mohan':777777777} • >>phonebook • >> {'Rock': 999999999, 'Rashmi': 888888888, 'Mohan':777777777} • >>Phonebook['Rock‘] • >>999999999
Modifying aDictionary >> phonebook = {'Rock': 999999999, 'Rashmi': 888888888, 'Mohan':777777777} >> phonebook['Rock‘] =666666666 >> phonebook >> {'Rock': 666666666, 'Rashmi': 888888888, 'Mohan':777777777} >> phonebook['Ricky'] =3333333333 >>phonebook >> {'Rock': 999999999, 'Ricky': 3333333333, 'Rashmi': 888888888, 'Mohan':777777777}
Methods inDictionary dict.keys() >> phonebook = {'Rock': 999999999, 'Rashmi': 888888888, 'Mohan':777777777} >> phonebook.keys() >> ['Mohan', 'Rashmi','Rock'] dict.values() >> phonebook = {'Rock': 999999999, 'Rashmi': 888888888, 'Mohan':777777777} >> phonebook.values() >> [777777777, 888888888,999999999]
dict.items() • >> phonebook = {'Rock': 999999999, 'Rashmi': 888888888, 'Mohan':777777777} • >> phonebook.items() • >> [('Mohan', 777777777), ('Rashmi', 888888888), ('Rock',999999999)]
dict.clear() >> phonebook = {'Rock': 999999999, 'Rashmi': 888888888, 'Mohan':777777777} >>phonebook.clear() >>phonebook >>{}
dict.copy() >> phonebook = {'Rock': 999999999, 'Rashmi': 888888888, 'Mohan':777777777} >> newPhoneBook =phonebook.copy() >> newPhoneBook >>{'Rock': 999999999, 'Rashmi': 888888888, 'Mohan':777777777}
dict.get(key) • >> phonebook = {'Rock': 999999999, 'Rashmi': 888888888, 'Mohan':777777777} • >> phonebook['Akshay'] • >> phonebook.get('Mohan')
in keyword: • > >> phonebook = {'Rock': 999999999, 'Rashmi': 888888888, 'Mohan':777777777} • >> ‘Akshay’ inphonebook • >> False • >> ‘Rock’ inphonebook • >> True
Practice Write a program to read the student and marks and make adictionary SampleInput: Enter the details : Mahesh20 Output: {‘Mahesh’ : 20}
Practice 2. Write a program to read the names from the user and make a list of names , then loop through the list of name and ask foremail. Make a dictionary ofname,email Sample Input: Output:
Tuples • A tuple is a sequence of immutable Pythonobjects. • Tuples are sequences, just likelists. • Any constant data that won’t change , better to usetuple • >> tup1 =() • >> tup2 = ('physics', 'chemistry', 1997,2000) • >> tup3 = (1, 2, 3, 4, 5) • >> tup4 = "a", "b", "c", "d"
Accessing items inTuple • Item can be access using the index • >> languages =('Hindi','English','Telugu','Gujarati','Marathi') • >>languages[0] • >> 'Hindi' • Slicing can be used inTuple • >> languages[0:3] ('Hindi', 'English','Telugu')
Simple example ofTuple • Swapping ofnumbers: • >> a= 1 • >> b =2 • >> temp =a • >> a =b • >> b =temp • >>a 2 • >>b 1 • >> a =1 • >> b =2 • >> a, b = b,a • >>a • 2 • >>b 1
Set • Sets are unordered collections of simpleobjects • Unique collections of immutableobjects • Define aSet: • >> set1 =set() • >> set2 ={'Ramesh','Mahes','Suresh'} • >> country =set(['India','America','Africa']) • >> country • >> set(['Africa', 'America', 'India','China'])
Methods inSet • Set.add(element) • >> set2 ={'Ramesh','Mahes','Suresh'} • >>set2.add('Himesh') • >>set2 • >> set(['Himesh', 'Ramesh', 'Suresh','Mahes'])
copy • >> names ={'Ramesh','Mahesh','Suresh'} • >> new_names =names.copy() • >> new_names • >> set(['Mahesh', 'Ramesh','Suresh'])
clear • >> names ={'Ramesh','Mahesh','Suresh'} • >>names.clear() • >>names • >>set([])
difference • >> x ={"a","b","c","d","e"} • >> y ={"b","c"} • >>x.difference(y) • >> set(['a', 'e','d'])
discard(ele) • >> x ={"a","b","c","d","e"} • >>x.discard("b") • >>x • >> set(['a', ‘c', 'e','d'])
remove(ele) • >> x ={"a","b","c","d","e"} • >>x.remove("b") • >>x • >> set(['a', ‘c', 'e','d'])
intersection • >> x ={"a","b","c"} • >> y ={"d","e"} • >>x.intersection(y) • >>set([]) • >>y.add("b") • >>x.intersection(y) • >> set(["b"])
union • >> x ={"a","b","c"} • >> y ={"d","e"} • >>x.union(y)
issubset • >>> x ={"a","b","c"} • >>> y ={"d","e"} • >>> z = {"b","c"} • >>>y.issubset(x) False • >>> z.issubset(x) True
issuperset • >>> x = {"a","b","c","d"} • >>> y = {"c","d"} • >>> x.issuperset(y) True • >>> y.issuperset(x) False
pop() • Remove and return an arbitrary setelement. • >>> x ={"a","b","c","d"} • >>>x.pop() • >>>‘a’