Python Data structures & Functions

 Data Structures in Python:

List:

List is a data structure in python that holds an organized collection of items. Items with in list always be accessed by index.

Ex:

fruits=[ 'Mango' , 'Banana' , 'Grapes' , 'Apple']

Tuple: 

Tuple is a immutable list, means if it once defined it cannot be modified. Items with in tuple also accessed by index as like list.

Ex: 

days_of_week=('Monday', 'Tuesday' , 'Wednesday' , 'Thursday' , 'Friday' , 'Saturday' , 'Sunday')

* Difference b/w List and Tuple:

In list you can add, remove and change the values but none of these will perform by tuple.

Set:

Set is data structure that contains an unordered collection of unique and mutable objects. Set can perform mathematical operations like Union, Intersection, Difference etc..

Ex:

A={1,5.2,4,3,6}       or    A= set(1,5,2,4,3,6)

* Difference b/w Set and Tuple:

In tuple we have index but, in set there is no indexing, objects in set can be changed.

Dictionary:

A dictionary holds key-value pairs, which are referred as items while other data types only contains elements.

Ex:

Student_roll number = { 'Rajesh' : 1 , 'Rama' : 2 , 'Krishna' : 3 }

here, names are keys and numbers are values. 

Function:

Instead of repeating several lines of code every time you want to perform a particular task, use a function that will allow you to write a block of python code once and then use it as many times. This can help you, reduce the overall length of your program.

To create function, use the def keyword followed by the name of the function. By simply calling the name of the function(you defined) reuse for that particular task.

def function_name():

Ex:

def even_or_odd(number):

          if number % 2 ==0:

                   return 'Even'

           else:

                   return 'Odd'


Anonymous function or Lambdas:

A function without  a name is called 'anonymous function' , means anonymous functions are not defined using 'def '. They are defined using the keyword 'lambda' and hence they are also called 'Lambda functions'.

Ex:

>>> print( lambda x : x*x) (5)

>>> 25


Comments