Data Structures using Python
python has 5 built-in data structures list, tuple, dictionary, set.
These can be categorized into two types
Ordered built-in data structures:
In this type of data structure, we can expect the data to be stored based on an index starting from 0 indexes. These are storing data in contagious manners.
a. List b. Tuple
Explanation:
a. List data structure : List data structure is linear sequence data structure. We can access the data items using the index. It follows the index based approach starting index from 0. It is dynamically typed data structure as we are not needed to define the length of the list. We can store the data items of heterogeneous data types i. e, It can store the int,float,string,listobject,tupleobject,dictionaryobject,setobject,tupleobject.List data structure is a mutable data structure.
CRUD operations on List Data Structure
- Create Operation: We can create a list using built-in function or by defining the list of items (these may or may not be same datatype) enclosed with [] assigning to a variable
Sample Code:
output::# Creating a list using built-in funtion numbers = list() #Creating a list by defining the list of items( these may or may not be same datatype) enclosed with [] to a variable dataitems = [1,2,3,4,"bob","alex",2.3,2,3,4,2] colors = ["Red","Green","Yellow"] dup_colors = colors.copy() # it will store a shallow copy of the colors list items. print(dup_colors)
[] [1, 2, 3, 4, 'bob', 'alex', 2.3, 2, 3, 4, 2] ['Red', 'Green', 'Yellow'] ['Red','Green','Yellow']
- Read Operation: We can read list items using print statement and count() funtion we can do with so many other built-in functions like list.copy() etc ..
Sample Code:
Output:print("List items after appending the 5 and \"Cotton business\" to the list:\n",dataitems) #Couting the number of times the value 2 present in the list count = dataitems.count(2) print("Occurence of value 2 in list: \n",count) print(dataitems[1:]) # It is called slicing from 1-index inclusion till the length of the list items can be accessed get printed. print(dataitems[::2]) # It will print the list items taking the step index=2 from 0 to length of listobject.
List items after appending the 5 and "Cotton business" to the list: [1, 2, 3, 4, 'bob', 'alex', 2.3, 2, 3, 4, 2] Occurence of value 2 in list: 3 [2, 3, 4, 'bob', 'alex', 2.3, 2, 3, 4, 2] [1, 3, 'bob', 2.3, 3, 2]
- Update operation: Inserting the Data item "batman" at index 1 so the remaining element in the list will move to the right Ex:: list.insert(index, obj). Adding the element to the end of the list using the append() function Ex:: listobj.append(obj).Extending the source list with the newly existed list items using the extend() function Ex:: listobj.extend(listobj) it will update the source list with the new list items.
Sample Code:
Output:#inserting the Data item "batman" at index 1 so the remaining element in the list will move to the right Ex:: list.insert(index, obj) #Adding the element to the end of the list dataitems.append(5) dataitems.append("Cotton business") print("List items after appending the 5 and \"Cotton business\" to the list:\n",dataitems) dataitems.insert(1,"batman") print("List items after insertion batman at index 1:\n",dataitems) #Extending the one List with other List using the list.extend(other_list) #so the list is source list having the updated data items of other_list list values dataitems.extend(colors) #After extending the dataitems list with the list colors list print("After extending the dataitems list with the list colors list::\n",dataitems) #Appending the dictionary object and set object to the list dataitems. dataitems.append({"1":"Kanchana"}) dataitems.append((12,3)) print(dataitems)
List items after appending the 5 and "Cotton business" to the list: [1, 2, 3, 4, 'bob', 'alex', 2.3, 2, 3, 4, 2, 5, 'Cotton business'] List items after insertion batman at index 1: [1, 'batman', 2, 3, 4, 'bob', 'alex', 2.3, 2, 3, 4, 2, 5, 'Cotton business'] After extending the dataitems list with the list colors list:: [1, 'batman', 2, 3, 4, 'bob', 'alex', 2.3, 2, 3, 4, 2, 5, 'Cotton business', 'Red', 'Green', 'Yellow'] [1, 'batman', 2, 3, 4, 'bob', 'alex', 2.3, 2, 3, 4, 2, 5, 'Cotton business', 'Red', 'Green', 'Yellow', {'1': 'Kanchana'}, (12, 3)]
- Delete operation: To remote an element/item from the list we can use the listObject.pop() to pop the last item from the list It will return the popped value. By using the listObject.pop(index) to remove the particular index value can be removed from the list. We can also remove an item from the list with passing the item to remove using the remove() funtion Ex: listobject.remove(obj). With the help of del keyword we can delete the entire list data structure object.To make a note here that after the
del listobject
operation we are no longer able to access listobject.If we try to access that list object we get the error type NameError Ex:: NameError: name 'listobject' is not defined. To empty the list use listobject.clear() function. Sample Code:
Output:# listObject.pop() to pop the last item from the list It will return the popped value print("pop the last item from the list::\n",dataitems.pop()) # listobject.remove(obj) to remove the "bob" item from the list dataitems.remove("bob") print("List items after removing the \"bob\" from the list::\n",dataitems) del dataitems # it will delete the entire list datastructure object.
b. Tuple data structure : Tuple data structure is an immutable data structure. We can create the tuple object after that we can not update the tuple object.We can perform a read operation and deleting the entire tuple object.It is also following the same index based approach starting from 0-index.It is also a dynamically typed data structure as are not in need of defining the length of the data structure.pop the last item from the list:: (12, 3) List items after removing the "bob" from the list:: [1, 'batman', 2, 3, 4, 'alex', 2.3, 2, 3, 4, 2, 5, 'Cotton business', 'Red', 'Green','Yellow',{'1': 'Kanchana'}]
CRD operations on Tuple Data Structure
- Create and Read Operation: We can create the tuple data strucure by the below approaches.Reading through the print statement,len(),max(),min(),slicing,by index.
Sample Code::
Output:#Tuple Data Strucure # Create Operation colors = ["red","blue","green"] names = "bob marley", laptops = "dell","ASUS","APPLE","HP" numbers = (1,2,3,4) dataitems = (12,13,"tomatoes",2.3,"Berry") randomdata = (12,13,(13,15),{"h":"Hai"},{1,3,4},[1,2,"Dark Night"]) new_colors = tuple(colors) # converting the list to tuple. empty_tuple = tuple() # creating an empty tuple # Read Operation print(names) print(laptops) print(numbers) print(dataitems) print(randomdata) print(new_colors) print("length of the tuple::\t",len(randomdata)) print("Max number from {} is {}".format(numbers,max(numbers))) print("Max number from {} is {}".format(numbers,min(numbers))) #print("Reverse the List {} is {} ".format(colors,colors.reverse())) i,j=0,3 print("Length of tuples names:{} laptops:{} numbers:{} dataitems:{} randomdata:{}". format(len(names),len(laptops),len(numbers),len(dataitems),len(randomdata))) print("Accessing based on index names[0]:{} laptops[0]:{} numbers[0]:{} dataitems[0]:{} randomdata[0]:{}". format(names[0],laptops[0],numbers[0],dataitems[0],randomdata[0])) print("Accessing based on index from {} to {} names[{}:{}]:{} laptops[{}:{}]:{} numbers[{}:{}]:{} dataitems[{}:{}]:{} randomdata[{}:{}]:{}". format(i,j,i,j,names[i:j],i,j,laptops[i:j],i,j,numbers[i:j],i,j,dataitems[i:j],i,j,randomdata[i:j]))
('bob marley',) ('dell', 'ASUS', 'APPLE', 'HP') (1, 2, 3, 4) (12, 13, 'tomatoes', 2.3, 'Berry') (12, 13, (13, 15), {'h': 'Hai'}, {1, 3, 4}, [1, 2, 'Dark Night']) ('red', 'blue', 'green') () length of the tuple:: 6 Max number from (1, 2, 3, 4) is 4 Max number from (1, 2, 3, 4) is 1 Length of tuples names:1 laptops:4 numbers:4 dataitems:5 randomdata:6 Accessing based on index names[0]:bob marley laptops[0]:dell numbers[0]:1 dataitems[0]:12 randomdata[0]:12 Accessing based on index from 0 to 3 names[0:3]:('bob marley',) laptops[0:3]: ('dell', 'ASUS', 'APPLE') numbers[0:3]:(1, 2, 3) dataitems[0:3]:(12, 13, 'tomatoes') randomdata[0:3]:(12, 13, (13, 15))
- Delete operation: We can delete the tuple object using th del statement.If we access after the object deletion it will throw NameError.
Sample Code:
# Delete Operaion del colors #print(colors) tuple object colors is deleted if we try to access we get NameError
- Create and Read Operation: We can create the tuple data strucure by the below approaches.Reading through the print statement,len(),max(),min(),slicing,by index.
Sample Code::
- Create Operation: We can create a list using built-in function or by defining the list of items (these may or may not be same datatype) enclosed with [] assigning to a variable
Sample Code:
Un-ordered built-in data structures:
In this type of data structure, we can store the data based on hashing which is being implemented internally by the Python interpreter.
a. Dictionary
b. Set