Tuesday, July 21, 2020

Data structure & their functions

Python has four types of data structure.
1. LIST
2. TUPLE
3. SET
4. DICTIONARY


List: The list is the data structure of item which are ordered, mutable and these are comma the separated value stored in square bracket.


The basic operation of List and functions:

1.   Accessing elements –[0],[1],[2],[3],[4].

2.   Modifying individuals item- You can modify in the list individually users[0], users[-2].

3.   Adding elements- You can add elements in the list by users. append.

4.   Removing elements- you remove any item by their position or value of the item. users.remove(‘list_iem_name’).

5.   List length-  len() functions return the number in list.

6.   Sorting a list –You can sort list increasing or decreasing order
Sorting permanently => users.sort(),users.sort(reversed=True)
Sorting temporary=> print(sorted(usres)),print(sorted,reversed=True))

7.   Slicing a list: You can slice a portion of the list [:3],[1:3],[-3:]

8.   Copying a list => copy_users=[:]

#some example of List
users=['val','bob','mia','ron','ned']
first_item=users[0]
print(first_item)
# sorting a list permanently
users.sort()
print(users)
users.sort(reverse=True)
print(users)
# for usrers in users:
#      print(users)
# finding length of the list
num_users=len(users)
print(num_users)
# slicing a list
first_three=users[:3]
print(first_three)
midle_three=users[1:4]
print(midle_three)
last_three=users[-3:]
print(last_three)

# copying a list
copy_of_users=users[:]
print(users)


   Tupple: Tuple is a set of an item which is ordered and immutable ().

Due to immutable in nature, we can’t apply so many functions like a list.
only count and index functions are there.




   Set: Set is data structured which is ordered, mutable in nature, and does not hold the duplicate value in the set.

Operations and functions of Set:
(A)          Creating a set :{}
1.   Duplicate element-does not hold the duplicate element in set.
2.   Mutable -but may not contain mutable items like a set, or even a dictionary.
3.   Python set function
(B).Accessing a set in python: Since the set is not support indexing so we can access the entire set at once. Because set does not support slicing so we can’t access the element one by one or [:3].
(C).Deleting a set: Because the set is not indexed then we can’t delete any element from the set. By using some method we can remove or discard any item from the set.
        Set. Pop() ->It will pop an element from beginning one by one
        Set. Clear() -> It will clear all the element from set.


(D). updating a set: You can add and update the number in your set.

          (E) Function on sets:
          Len()->The len function return the length of the functions.
          Max() ->This function can return the highest value from set.
          Min()->This function can return the Lowest value from the set.
          Sum()->This function sum all the value from the set.
          All/any()->True or False
          Sorted()->It will sort the item in ascending order.






(E).Methods on set:

          Union(),Intersection(),difference(),symmetric_difference,intersection_update,difference_updat
          Symmetric_difference_update() ,copy,isdisjoint,issubset,issuperset,
          (F).Operation on sets:
Membership: We can apply the ‘in’ and ‘not’ in python operator on items for set. This tells us weather they are belong to set.
(H): Iterating on set: We can iterate on set in a for a loop. 

(I): The frozenset: A frozenset is in-effect an immutable set. You can’t change its value. Also, a set can’t be used a key for a dictionary , but a frozenset can


d=set()
print(type(d))
# =========Deleting===========
# we can't delete any item from the list but by suing discard or delete method we can
set={1,3,3,4,5,5,7}
set.discard(
3)
print(set)
set.remove(
5)
print(set)
# pop()
set.pop()
print(set)
# clear
set.clear()
print(set)
# Updating a set
numbers={1,1,2,2,3,3,4,5}
# numbers[9]
# print(numbers)
numbers.add(3.5)
print(numbers)
numbers.update([
7,8],[1,10,9])
print(numbers)
# Functions on set
print(len(numbers))
print(max((numbers)))
print(min(numbers))
print(sum(numbers))
print(any(numbers))
print(all(numbers))
print(sorted(numbers))
# Methods on set
set1,set2,set3={1,2,3,4},{4,5,6},{4,5,7,8,9}
print(set1.union(set2,set3))
print(set2.intersection(set3))
print(set1.difference(set2))
print(set1.symmetric_difference(set2))
print(set1.intersection_update(set2))
print(set1.difference_update(set2))
print(set1.symmetric_difference_update(set2))
print(set3.copy)
print(set1.isdisjoint(set3))
print(set1.issubset(set2))
print(set1.issuperset(set1))
# Operation on set
# 'p' in {'a','c','p','d'}
for i in {'a','c','p','d'}:
   
print(i)




Dictionary: A dictionary has to contain key-value with semicolon pair in the curly bracket.




Creating a dictionary: dict = {‘a’:1,’b’:2,’c’:3}
(A): Python dictionary with comprehension: It’s just like range function.
mydict={x*x:x for x in range(8)}
     print(mydict)
     output= {0: 0, 1: 1, 4: 2, 9: 3, 16: 4, 25: 5, 36: 6, 49: 7}
(B): Dictionary with mixed keys: The key-Val pair should not sa me necessary in dictionary.
dict3={1:'carrots','two':[1,2,3]}
(C)dict(): Using dict function we can convert in dictionary.
dict(([1,2],[2,4],[3,6]))

(D): Declaring one key more than once: Like set dictionary can’t hold more than one key.
mydict2={1:2,1:3,1:4,2:4}

(E):Declaring empty dictionary and adding elements later: When you can add key-value pair in dictionary.
animals={}
animals[1]='dog'
animals[2]='cat'

(F)Accessing python dictionary:
(a)accessing an entire python dictionary: print the dict name
(b)accessing a value: To access an item from a dictionary we can use square bracket in the dictionary.
(c)get(): The Python dictionary get() functions takes a key as an argument and returns the corresponding value.
  Mydict.get(49)
Output=7
(G): Updating the value of an Existing key: you can update the dictionary value by using square bracket.
(H)You can delete the item from dict like-  del dict[2]
(I) In-built functions on dictionary:
Len(),any()->return true if any key has Boolean value.
All(),sorted() ->function returns a  sorted sequence key in ascending order dictionary.

(J)In-built methods of dictionary:
Keys()-> used for return the key of dictionary
Values()-> used for return the value of dictionary
Items()->return the key-value of dictionary
Get()->dict4.get(3,0 ) it will return the key if there is in dictionary or return 0.
Clear()->represent the empty  dictionary
Copy()->copy methods creates the shallow copy of the python dictionary.
Pop()->This method is used to remove and display an item from the dictionary. It takes one to two arguments. The first is the key to be deleted, while the second is the value that’s returned if the key isn’t found.
Popitem(): pop item() method is such that for a particular dictionary, it always pops pairs in the same order.
From keys()->This method creates a new Python dictionary from an existing one.

Update():This method is used for updating the dictionary as a key value.


Python Dictionary Operation:
Membership: We can apply the ‘in’ and ‘not in’ operators on a Python dictionary to check whether it contains a certain key.


Python Iterate dictionary: When in a for loop, you can also iterate on a Python dictionary like on a list, tuple, or set.





Nested Dictionary: Finally, let’s look at nested dictionaries. You can also place a Python dictionary as a value within a dictionary.  , dict1={4:{1:2,2:4},8:16}

# dictionary -contain key-value pair
dict={x*x:x for x in range (8)}
print(dict)
# updating the value of the existing key
dict1={1:2,3:4,5:6,7:8}
dict1[
3]=#You can update the value by assigning key in square bracket
print(dict1)
# Deleting a dict
del dict1[3]
print(dict1)




Difference between List, Tuple, Set  &  Dictionary



List
Tupple
Set
Dictionary
List is a collection that is ordered, mutable.
Tupple is a collection that is ordered, immutable.
Collection of Unordered and Unindexed items & mutable in nature.
A dictionary is a the collection which is unordered, changeable and indexed & Key: Value Pair in Python.
Allows duplicate members[]

Tuples are faster than lists as they are immutable& hold the duplicacy().
Does not take duplicate Values{}.
Does not take duplicate Values{}.

Lists are like arrays declared in other languages.


Sets are not faster than lists however they have an upper hand when it comes to membership testing.

Functios:append,remove,len
Sort,slicing,copy,pop


Functions: not support like list due to immutable in nature.
Functions:len,max,min,sum,all,
Any, sort, pop clear, delete
Functions:len ,all
Sorted,keys,values,items,get,
Clear, copy




1 comment:

  1. Really explains everything in detail, the article is very interesting and effective. Otherwise any one who want to learn python core to advance contact us on 9311002620 or visit :-https://www.htsindia.com/Courses/python/python-training-institute-in-south-delhi

    ReplyDelete