Uploaded by delphy.p

UNIT IV PYTHON

advertisement
list
 A list consists of items separated by commas and enclosed within square brackets ([]).
 A list can have values of different data types
 Each value in the list has an index. The index of the first element of the list is 0, the index of the second
element is 1 and so on. The values can be accessed using the index
SYNTAX:
List_variable=[val1,val2,……………]
>>> a = [1, 'selva', 45.6, 55]
>>> b = [2]
>>> print(a)
[1, 'selva', 45.6, 55]
>>> print(a[0])
1
>>> print(a[1])
selva
list
>>> print(a*2)
[1, 'selva', 45.6, 55, 1, 'selva', 45.6, 55]
>>> print(a + b)
[1, 'selva', 45.6, 55, 2]
list class (or) list data type
 Lists can be nested
Eg: a = [‘word’, 2.0, 5, [10, 20]]
 Lists are mutable – the values in a list
can be changed
>>> print(a[3])
>>> numbers = [42,123]
[10, 20]
>>> print(numbers)
>>> print(a[3][0])
[42, 123]
10
>>> print(a[3][1])
20
>>> numbers[1] = 5
>>> print(numbers)
[42, 5]
Access values in the list
• List can be sliced and concatenated.
• To access the values in the lists ,square brackets are used to slice
along with the index or indices to get values stored at that index.
• The slice operator [n:m] returns the part of the string from the n'th
character to the m'th character, including the first but excluding the
last. In other words, start with the character at index n and go up to
but do not include the character at index m
• Seq=list[start:stop:step]
• Seq=list[start:stop]
Updating values in the list
• we can also append new values in the list and removing the existing
values from the list using
• append(),insert() method and del statement &pop() for removing a
values in the list.
Nested list
• Nested list means a list within another list.
• Example:
• list=[10,30,45,”hello”,[2,3,4,5],67,9.0]
• It consist of different datatypes.
aliasing
• When we assign one variable/object to the other, both of them are
actually point the same variable/object in the memory.
• Both objects points to the same list in a computer memory
Cloning lists
• If we want to modify the list and also keep a copy of the original
list,then you should create a separate copy of the list.
• This process is called “cloning”
LIST OPERATIONS
• len():
• Return the length of the list.
• Concatenation:
• Join two lists
• Repetitions:
• Repeat the element in the list
• min() :
• Print minimum value in the list
• max():
• Print maximum value in the list
• In:- Check the value is present in the list
• Not in-check the value is not present in the list
• Sum:-add the value in the list
• All:-return True If all elements of the list are True(or if list is Empty)
• Any:-Return True if any element of the list is True.if the list is empty
,returns False.
• sort:returns the sort list.
List methods
Looping in list
The “for” var in list statement is an easy way to access each element in
a list.
For Example: in the following code,the for loop is used to access each
item in the list.
for i in list
print(i)
Using range() Function
• If you need to print the index ,the you can use the range()function as
shown in the code below.
Using enumerate() function
• When you want to print the index as well as an item in the list.
• The enumerate()function returns an enumerate object which
contains the index and value of all the items.
List Parameters
Tuple
• A tuple is similar to the lists as it is also contains of a numbers of
values separated by commas and enclosed within paranthesis.
Syntax:
Tup1=(val1,val2………….)
• Tuple is a sequences of immutable.
• The main differences between the list and tuple is that you can
change the values in the list not in the tuple.
• Tuple is a read-only data type that list is not.
• If we try to edit the data in the tuple, Tup[2]=456,it will generate the
error.
Program to demonstrate operations of Tuple
Necessity of having a comma in tuple
Accessing values in tuples
Updating Tuple
Deleting the tuple
• Tuple is an immutable data structure.we cannot delete values from it.
• We can always delete the entire tuple by using the del statement.
Tuple Assignment
• It allows the tuple of variables on the left side of the assignment
operator to be assigned values from a tuple given on the right side of
the assignment operator.
Statements – Tuple assignment
Conventional assignments to swap two variables, a and
b
>>>temp = a
>>>a = b
>>>b = temp
Tuple assignment to swap a and b
>>> a, b = b, a
Tuple as return value
• We need to return more than one value from a function
Nested Tuples
• Tuple inside the tuple-nested tuple.
Index() method
Counting the elements:count()method
• The count method is used to return the number of elements with the
specific value in the tuple.
Zip() function
• zip()is a built-in function that takes two or more sequences and
“zips”,them into a list of tuples.
Dictionary
•
•
•
•
•
•
•
•
Dictionaries are used to store data values as the pair of key and value.
Dictionary_name={key1:value1,key2:value2,……..}
The key -strings
Value-Any data type
The key- value pairs are enclosed with curly braces{ }
Each key-value pair is separated by the other using a colon :
To access any value in the dictionary, we need to specify its key square braces([])
It is used for fast retrieval of data.
• Example:
Add an entry
Modifying the entry
Deleting the items
• Syntax:
del dictionary_variable[key]
Using pop()
Using popitem()
Sorting items in a dictionary
Nested Dictionaries
• Dictionary inside the dictionary is called as nested dictionaries.
Dictionary using Set()
• Set1=set([“arun”,”arul”,”babu”,”raja”])
• Set2=set() //empty set
ADDING ELEMENTS IN SET 2:
Set2.add(“babu”)
Set2.add(“arul”)
Set2.add(“vinoth”)
Now set2=([“babu”,”arul”,”vinoth”])
• UNION OF TWO SETS: // joining two sets
SYNTAX: Set1|set2
Output:
{“arun”,”arul”,”babu”,”raja”,”babu”,”arul”,”vinoth”}
• INTERSECTION OF TWO SETS: //Common element
SYNTAX:
Set1&set2
OUTPUT:
{“ARUL”,”BABU”}
• DIFFERENCES OF TWO SETS:
• Syntax: set1-set2
Output: {“arun”,”raja”}
• Syntax: set2-set1
Output
{“vinoth”}
Dictionary operations&functions
• len(dict):
• Str(dict):
dict.copy()
• dict.items() and dict.values()
• dict1.update(dict2):
• dict1.values()
• in and not in
Advanced list processing
PROGRAM TO MAKE LIST OF CUBES
List comprehensions:
• Python also supports computed lists called “list comprehensions”
having the following syntax:
• List=[expression for variable in sequences]
• List comprehension is also used to create a subsequences of those
elements that satisfy a certain conditions.
ILLUSTRATIVE PROGRAMS:STUDENT MARK STATEMENT
HISTOGRAM-ILLUSTRATIVE PROGRAM
• A histogram is basically used to represent data provided in a form of
some graph.
• It is accurate method for the graphical representation of numerical
data distribution.
• It is a type of bar plot where X-axis represents the bin ranges while
Y-axis gives information about frequency
(Bins are the number of intervals you want to divide all of your data into, such
that it can be displayed as bars on a histogram)
• It is a graph showing the number of observations within each given
interval.
Example: Say you ask for the height of 250 people,
you might end up with a histogram like this:
Basic libraries :
• numpy
• numPy is a Python library used for working with arrays.
• It also has functions for working in domain of linear algebra, fourier
transform, and matrices.
• matplotlib
matplotlib is a low level graph plotting library in python that serves as
a visualization utility.
• pandas
Pandas is a Python library used for working with data sets. It has
functions for analyzing, cleaning, exploring, and manipulating data.
Multi line plots
With grid
RETAIL BILL PREPARATION-ILLUSTRATIVE PROGRAM
Output:
ILLUSTRATIVE PROGRAM-SIMPLE SORTING
• Selection sort:
• The selection sort select the smallest element in the list.
• When the element is found,it is swapped with the first element in the
list.
• Then the second smallest element in the list is searched.
• This condition is repeated until we got sorted array.
Insertion sort:
• Insertion sort is a sorting algorithm that places an unsorted element
at its suitable place in each iteration.
• Insertion sort works similarly as we sort cards in our hand in a card
game.
• We assume that the first card is already sorted then, we select an
unsorted card. If the unsorted card is greater than the card in hand, it
is placed on the right otherwise, to the left. In the same way, other
unsorted cards are taken and put in their right place.
• A similar approach is used by insertion sort.
Bubble sort
• Bubble sort is a sorting algorithm that compares two adjacent elements and swaps them until
they are in the intended order.
• A Bubble sort is an easy algorithm among the various sorting algorithms.
• Just like the movement of air bubbles in the water that rise up to the surface, each element of the
array move to the end in each iteration. Therefore, it is called a bubble sort.
• We learn it as a first sorting algorithm. It is easy to learn and highly intuitive. It can be easy to
implement into the code, which is much beneficial for beginner software developers.
• But it is the worst algorithm for sorting the elements in every except because it checks every time
the array is sorted or not.
Merge sort
• Merge Sort is one of the most popular sorting algorithms that is
based on the principle of Divide and Conquer Algorithm.
• Here, a problem is divided into multiple sub-problems.
• Each sub-problem is solved individually. Finally, sub-problems are
combined to form the final solution.
Download