Complex Datatype of PYTHON

In Previous Post we have discussed about Big User of Python. Today we going to talk about The complex Datatypes in Python.


DATA TYPE
First of all we should know about datatype. exactly what you think about datatype, what is it, why it is used

There is a feature of datatype or type data that tells the compiler or interpreter how the programmer wants to use the data. Most programming languages ​​support the real, integer,character and Boolean common datatypes. A datatype prevents those values ​​that can take an expression, such as a variable or function. This data type defines the operations that can be done on the data, the meaning of the data, and the values ​​of that type can be stored. A type of value from which an expression can take its value
In python we also have Built-in Datatype like Integer,string,float which also called primitive Datatypes.These are same in most of programming language that's why we are not discuss it yet.

Complex Datatypes

There are main 3 complex datatype in python which is namely ............
  1. List
  2. Tuple
  3. Dictionary
  4. Set

1) List

  • List is Just Like a array in C language.
  • List is very useful type in python.
  • Python list contains Series of values on it.
  • In python list we can also store complex datatype like tuple,dictionary and list itself.
  • List is mutable type, It means we can edit it after storing something.
  • to create list square-brackets'[]' are used.

* How to create list

  • If we want to use list we should first create it ;)
  • To create list in python we can use list() function.
  • list() has only one parameter which is iterable that could be a  sequence (string, tuples) or collection (set, dictionary) or iterator object
  • its also optional variable.
  • List() constructor returns a editable list of elements in sequence manner.

#List_program.py
(Save it and execute to understand about list() function)

#to create empty list
print(list())

#To create list from any string
blogname = "Pythonist"
print(list(blogname))
#################################################
  • We can also create list using '[ ]'
Syntax : var_name = ['val1', 'val2',.......,'valN']

-> This way is like To create an any variable
-> For creating list we use square bracket.
-> For value separation we use comma.

#List2_program.py
(Save it and execute to understand about list creation)

#Normal list which contain string values
Lang = ["c","Python","java","php","assembly"]
print(Lang)

#List which contain some complex datatypes
strange = [1,(2,3),[4,5],False,'Thank You']
print(strange)
#################################################

* Function of list

Insert(in,val):
  • This function is use to add any item in list.
  • Insert() function has two argument 1:position and 2:value
  • Using insert() function we can insert any item at particular position which is given by user
  • Syntax is : list_name.insert(index,value)

#list_insert.py
(Save it and execute to understand about insert() function)

#creating normal list which contain integers
list1 = [1,2,3,4,5]

#Show me the list
print(list1)

#i want to insert 9 at 2nd position
list1.insert(1,9)
#here first value is 1 but its 2 ;)

#once again show me the list
print(list1)
#################################################

Append(val):
  • This method add value in list.
  • Append() can add item at the end of the list.
  • Append() function can add one value at a time.
  • Append() has only one argument as you see it's value.
  • Syntax is : list_name.append(val)

#lis_append.py
(Save it and execute to understand about append() function)

#This time i created empty list :)
list1 = []

#just time-pass
print(list1)

#now to be serious
for i in range(1,10,2):
  list1.append(i)

#after append some value
print(list1)
#################################################

del/pop(index) :
  • This is keyword.
  • Del is use to delete any item or whole list.
  • Using del keyword we can control list.
  • Syntax is : del list/list[start:end]
  • Here in del we need to specify from where to where we want to delete elements in list its concept of slicing.
  • If we want to delete any specific element from list them we must use pop() function.
  • Pop() has one argument which is index.
#List_del.py
(Save it and execute to understand about insert() function)

#As usual we create list
list1 = []

for i in range(0,20,2):
  list1.append(i)

#justify value is their or not :)
print("list after loop : ")
print(list1)

#now use del weapon 
del list[:1] #it will remove first element of list which is 0

#simply print list
print("list after loosing one element by del: ")
print(list1)

#now i am using second weapon pop()
list1.pop(4)

#simply print list
print("list after loosing one element by pop(): ")
print(list1)

#this will delete whole list
#del list1

print(list1) #generate error because of we just deleted list
###########################################################

Index(item, start,end) :
  • This will work as their name
  • This function return first appear index from list for the given item
  • Here except first all the parameter is optional.
  • This function could use in searching purpose.
#List_index.py

#creation of list
list1 = [1,4,7,4,5,6,7,3]

#will print the most lowest index of 7
print(list1.index(7))

#print the first occurrence of 4
print(list1.index(4))
########################################################

Count(val) : 
  • This function will return how many time given value occurred in list
  • This function not count length of list
  • Syntax is : list_name.count(val)
#list_count.py

#create list which has many same values.
list1 = [1,1,1,2,3,4,5,3,2]

#now apply count function
print(list1.count(1))


########################################################

Sort()
  • This shows their work on it's name
  • This will sort any list in ascending order
  • If we want to sort in descending order we need to pass one argument which is "reverse=True"
  • Syntax is : list_name.sort()
#list_sort.py

#create many lists
list1 = list(range(1,10))

list2 = list("pythonist")

#first sort in simple way which is ascending order
print(list1.sort())

#list in reverse order
print("list in descending order :")
print(list2.sort(reverse=True))


########################################################

Copy() :
  • In list if we assign one list to another it will generate shadow of that list
  • That means if we modified one of them it will reflect on another on.
  • To overcome this problem we have copy function.
  • This function copy one list on another.
  • This function doesn't have any parameter.
  • Syntax is : list1 = list2.copy()
#list_copy.py

#create one list
list1 = list(range(0,20,2))

#create another list based on list1
list2 = list1.copy()

#formality based
print(list2)

list1.pop(10)

#after deletion list one is
print(list1)

#list2 is
print(list2)
#################################################
===========================

2) Tuple


  • Tuples are used to hold together multiple objects. Think of them as similar to lists, but without the extensive functionality that the list class gives you. One major feature of tuples is that they are immutable like strings i.e. you cannot modify tuples.
  • Tuples are defined by specifying items separated by commas within an optional pair of parentheses.
  • Tuples are usually used in cases where a statement or a user-defined function can
  • safely assume that the collection of values i.e. the tuple of values used will not change.
  • in below example we see some basic useful function of tuple.
#py_tuple.py

zoo = ('lion','tiger','python','deer','fox')

#to find out total element in tuple
print('Number of animals in the zoo is', len(zoo))

#we add some new animals in our zoo :)
new_zoo = 'monkey', 'camel', zoo

#How many cages we have in our new zoo
print('Number of cages in the new zoo is', len(new_zoo))

#list all animals on new zoo
print('All animals in new zoo are', new_zoo);

#to view which are the old animal in our new zoo
print('Animals brought from old zoo are', new_zoo[2])

#which animals are comes late in new zoo
print('Last animal brought from old zoo is', new_zoo[2][2])


#count total animals in new zoo
print('Number of animals in the new zoo is', \
len(new_zoo)-1+len(new_zoo[2]))
#################################################


    list
  • If we want to create empty tuple then we can use empty pair of parentheses.
    • myempty = ()
  • If we want to place only one element in tuple its not possible as only put element on tuple. we need to add extra comma sign after put element on tuple
    • singleton = (21,)
   ===========================

3) Dictionary

  • A dictionary is like an address-book where you can find the address or contact details of a person by knowing only his/her name i.e. we associate keys (name) with values (details). Note that the key must be unique just like you cannot find out the correct information if you have two persons with the exact same name.
  • Note that you can use only immutable objects (like strings) for the keys of a dictionary but you can use either immutable or mutable objects for the values of the dictionary.This basically translates to say that you should use only simple objects for keys.
  • Pairs of keys and values are specified in a dictionary by using the notation d = {key1 : value1, key2 : value2 } . Notice that the key-value pairs are separated by a colon and the pairs are separated themselves by commas and all this is enclosed in a pair of curly braces.
  • Remember that key-value pairs in a dictionary are not ordered in any manner. If you want a particular order, then you will have to sort them yourself before using it.
  • The dictionaries that you will be using are instances/objects of the dict class.
  • Like list dictionary is also mutable.


#py_dict.py

author = {
   "name": "sunil",
   "lastname": "Rathod",
   "birthyear": 1998
}

#we can also create dictionary using dict() constructor
author = dict(name="sunil",lastname="Rathod",birthyear=1998)

print(author)

#You can access the items of a dictionary by referring to its key name, inside square brackets
print("my name is : ",author["name"])

#or
print("my name is : ",author.get("name"))

#You can change the value of a specific item by referring to its #key name
author["lastname"] = "Shrimali"

#get all the keys name using loop
for key in author:
   print(key)

#get all the values using loop
for x in author:
   print(author[x])

#or
for val in author.values():
   print(val)

#get both the keys and values with the help of items() function
for key,val in author.items():
   print("key :",key,", values :"val)


#To determine if a specified key is present in a dictionary use #use the 'in' keyword
if "birthyear" in author:
   print("year is given in author")
else:
   print("birth year is not specified")

#to get length of dictionary(key-value pair)
print(len(author))

#Add new item in a dictionary
author["nationality"] = "Indian"

print(author)

#Remove any key-value pair from dictionary

#1 : remove using key
author.pop("lastname") # del author["lastname"]
print(author)

#2 : remove last inserted key-value pair from dictionary
author.popitem()
print(author)

#copy

'''You cannot copy a dictionary simple by typing dict2 = dict1, because: dict2 will only be a reference to dict1, and changes made in dict1 will automatically also be made in dict2.

There are ways to make a copy, one way is to use the built-in Dictionary method copy()'''

mydict = author.copy()
print(mydict)

#copy using dict() function
dict2 = dict(mydict)

#the clear() function empties the dictionary
dict2.clear()
print(dict2)

#to delete any dictionary use del keyword
del dict2
del mydict
print(mydict)

#the last print line cause error because mydict no longer #available
#you have to first comment this line




########################################################

   ===========================


Comments

Popular Posts