Python For AI - Unit II QB
Python For AI - Unit II QB
>>> t[:4]
Output:['a', 'b', 'c', 'd']
>>> t[3:]
Output:['d', 'e', 'f']
>>> t[:]
Output : ['a', 'b', 'c', 'd', 'e', 'f']
Example:
>>>a=[1,2,3]
>>>b=a[:]
>>>print b
[1,2,3].
6. What is Aliasing?
• More than one list variable can point to the same data. This is called an alias.
• If ‘A’ refers to an object and you assign ‘ B = A’, then both variables refer to the
same object:
>>> A = [1, 2, 3]
>>> B= A
>>> B is A
True
9. Define Tuples?
• A tuple is a sequence of values.
• The values can be any type, and they are indexed by integers, so in that respect tuples
are a lot like lists. The important difference is that tuples are immutable.
To create a tuple with a single element, you have to include the final comma:
>>> t1 = ('a',)
>>> type(t1)
<type 'tuple'>
• One of the unique features of the python language is the ability to have a tuple on
the left hand side of an assignment statement.
• This allows you to assign more than one variable at a time when the left hand
side is a sequence.
Example:
Two element in list (which is a sequence ) and assign the first and second elements of the
variables x and y in a single statement.
• A function can only return one value, but if the value is a tuple, the effect is the same as
returning multiple values.
Example:
>>> t = divmod(7, 3)
>>> print t
(2, 1)
Or use tuple assignment to store the elements separately:
>>> quot, rem = divmod(7, 3)
>>> print
quot 2
>>> print rem
1
.
5
Tuples Dictionaries
• A tuple is a sequence of values. • Python dictionary are kind of hash table
• The values can be any type, and they are type.
indexed by integers, so in that respect • Dictionary work like associative arrays
tuples are a lot like lists. The important or hashes found in perl and consist of
difference is that tuples are immutable. key value pairs.
• Dictionary is one of the compound data type like strings, list and tuple. Every element
in a dictionary is the key-value pair.
• An empty dictionary without any items is written with just two curly braces, like this: {}.
Example:
>>> eng2sp = {}
>>> eng2sp["one"] = "uno"
>>> eng2sp["two"] = "dos"
>>> print(eng2sp)
Output:
{"two": "dos", "one": "uno"}
• A dictionary can be Created by specifying the key and value separated by colon(:) and
the elements are separated by comma (,).The entire set of elements must be enclosed by
curly braces {}.
Dict={ }
6
Operation Description
cmp(dict1, dict2) Compares elements of both dict.
len(dict) Gives the total length of the dictionary.
type (variable) Returns the type of the passed variable. If passed variable is
dictionary,
then it would return a dictionary type.
Big Questions:
1. What is List Values? Describe about creating a list, accessing the values in list, deleting a
list, updating a list.
LIST VALUES:
CREATING A LIST:
There are several ways to create a new list, the simplest is to enclose the elements in square
Bracket [ ]
Output:
['Apple', 'Watermelon',
[]
DELETING A LIST:
➢ Any element in the list can be deleted, del removes an element from a list.
Example:
>>> a=(‘one’,’two’,’three’)
>>>del a(1)
>>>a
Output:
(‘one’,’three’)
UPDATING A LIST:
A slice operator on the left side of an assignment can update multiple elements:
>>> t = ['a', 'b', 'c', 'd', 'e', 'f']
>>> t[1:3] = ['x', 'y']
>>> print t
Output: ['a', 'x', 'y', 'd', 'e', 'f'].
2. Explain the basic List Operations and list slices in details with necessary
24. Lists respond to the + and * operators much like strings; they mean
concatenation and repetition here too, except that the result is a new list, not a
string.
LIST SLICES:
➢ A sub-sequence of a sequence is called a slice and the operation that
performs on subsequence is called slicing.
>>> t[:4]
Output:['a', 'b', 'c', 'd']
>>> t[3:]
Output:['d', 'e', 'f']
>>> t[:]
Output : ['a', 'b', 'c', 'd', 'e', 'f']
Since lists are mutable, it is often useful to make a copy before performing
operations.. A slice operator on the left side of an assignment can update multiple
elements:
[Link]( ): 2. [Link] ( )
9
5. [Link] ( ) 6. [Link] ( )
➢ [Link] ( ) method is used to return the ➢ [Link] ( ) method is used to sort
item at the given index position from the the items in the list.
list and the removes that item.
Example
Example X = [54, 12, 85, 65, 74, 90];
X = [123, 'xyz', 'zara', 'abc']; Print(“sorted list:”, [Link] ( ))
Print( “List 1 :”,[Link](0))
Print (“List 2: ”, [Link](3)) Output:
Output: Sorted list= [12,54 ,65,74,85,90]
Example Example
X = [123, 'xyz', 'zara', 'abc',’xyz’]; X = [123, 'xyz', 'zara', 'abc',’xyz’];
[Link]( ) X..clear( )
Print ( “List 1 :”,X) Print (X)
4. Discuss about the list loop, list mutability with examples.(8 mark)
• In List loop, we use a loop to access all the element in a list. A loop is a block of code
that repeats itself until it run out of items to work with or until a certain condition is
met.
• Our loop will run once for every item in our list,
List Mutability:
• Mutability is the ability for certain types of data to be changed without entirely recreating it.
• List is a mutable data type; which mean we can change their element.
• The syntax for accessing the elements of a list is the same as for accessing the
characters of a string—the bracket operator.
• The expression inside the brackets specifies the index. Remember that the indices start at 0.
1 →123
5
12
Fruit 0 → “Apple”
1 → “Grapes”
2 → “Orange”
• Lists are represented by boxes with the word “list” outside and the elements of
the list inside.
• Fruits refer to a list with three elements indexed 0, 1 and 2.
• Numbers contains two elements; the diagram shows that the value of the second
element has been reassigned from 123 to 5.
.
The in operator also works on lists.
>>> Fruit = ['Apple', 'Grapes', 'Orange']
>>> ‘Apple’ in Fruit
True
>>> ‘Watermelon’ in Fruit
False
#blue is change to
orange Colour_list [-2] =
“orange”
Print(colour_list)
Output:
Original List =[“red”, “green”, “blue”, “purple”]
[“pink”, “green”, “orange”, “purple”].
5. Discuss about the list aliasing, cloning list and list parameter with examples.
LIST ALIASING:
• Since variables refer to object, If ‘A’ refers to an object and you assign ‘ B = A’, then
both variables refer to the same object:
>>> A = [1, 2, 3]
>>> B= A
>>> B is A
13
True
• In this case, Diagram looks like this
[1,2,3]
• The association of a variable with an object is called a reference. In this example, there
are two references to the same object.
• An object with more than one reference has more than one name, then the object is
said to be aliased.
If the aliased object is mutable, changes made with one alias affect the other:
>>> B[0] = 9
>>> print A
[9, 2, 3]
• Although this behaviour can be useful, it is error-prone. In general, it is safer to
avoid aliasing when you are working with mutable objects.
In this example:
A = ('banana')
B=( 'banana')
It almost never makes a difference whether A and B refer to the same string or not.
CLONING LIST:
• If we want to modify a list and also keep a copy of the original, we need to be able to
make a copy of the list itself, not just the reference.
• This process is sometimes called cloning, to avoid the ambiguity of the copy.
• The easiest way to clone a list is to use the slice operator
>>>a=[1,2,3]
>>>b=a[:]
>>>print b
[1,2,3]
• Taking any slice, creates a new list. In this case the slice happens to consists of the
whole list.
• Now we are free to make changes to b without worrying about list ‘a’.
>>>b[0]=5
>>>print a
>>>print b
[1,2,3]
[5,2,3]
LIST PARAMETERS:
• Passing a list to a function, the function gets a reference to the list. If the function
modifies a list parameter, the caller sees the change.
For example, delete_head removes the first element from a list: def delete_head(t):
14
del t[0]
Here’s how it is used:
>>> letters = ['a', 'b', 'c']
>>> delete_head(letters)
>>> print letters ['b', 'c']
The parameter t and the variable letters are aliases for the same object. The stack diagram looks
like this:
Main Letters
0 → ‘a’
1 → ‘b’
Delete_head t 2 → ‘c’
6. Explain about tuples and also the concept of tuple assignment and tuples as return
value with example.
• A tuple is a sequence of values.
• The values can be any type, and they are indexed by integers, so in that respect tuples a
like lists. The important difference is that tuples are immutable.
➢ To create a tuple with a single element, you have to include the final comma:
>>> t1 = ('a',)
>>> type(t1)
<type 'tuple'>
➢ Another way to create a tuple is the built-in function tuple. With no argument, it
creates an empty tuple:
>>> t = tuple()
>>> print
(t) ( )
➢ If the argument is a sequence (string, list or tuple), the result is a tuple with the
elements of the sequence:
>>> t = tuple('lupins')
>>> print (t)
('l', 'u', 'p', 'i', 'n', 's')
➢ Because tuple is the name of a built-in function, avoid using it as a variable name.
➢ Most list operators also work on tuples. The bracket operator indexes an element:
>>> t = ('a', 'b', 'c', 'd', 'e')
>>> print
(t[0]) 'a'
And the slice operator selects a range of elements.
>>> print
t[1:3] ('b', 'c')
But if you try to modify one of the elements of the tuple, you get an error:
>>> t[0] = 'A'
TypeError: object doesn't support item assignment
➢ can’t modify the elements of a tuple, but you can replace one tuple with another:
>>> t = ('a', 'b', 'c', 'd', 'e')
>>>t = ('A',) + t[1:]
>>> print (t)
('A', 'b', 'c', 'd', 'e')
TUPLE ASSIGNMENT:
• One of the unique features of the python language is the ability to have a tuple on
the left hand side of an assignment statement.
• This allows you to assign more than one variable at a time when the left hand
side is a sequence.
In the below example , we have two element list (which is a sequence ) and assign the first and
second elements of the variables x and y in a single statement.
>>> m = ( ‘have’, ‘fun’)
>>> x,y= m
>>> x
‘have’
>>>y
‘fun’
• It is often useful to swap the values of two variables. With conventional assignments,
you have to use a temporary variable. For example, to swap a and b:
>>> temp = a
>>> a = b
>>> b = temp
Tuple assignment is more elegant:
>>> a, b = b, a
• The left side is a tuple of variables; the right side is a tuple of expressions. Each value
is assigned to its respective variable. All the expressions on the right side are
evaluated before any of the assignments.
• The number of variables on the left and the number of values on the right have to
be the same:
>>> a, b = 1, 2, 3
• A function can only return one value, but if the value is a tuple, the effect is the same as
returning multiple values.
• For example, if you want to divide two integers and compute the quotient and
remainder, it is inefficient to compute x/y and then x%y. It is better to compute them
both at the same time.
• The built-in function divmod takes two arguments and returns a tuple of two values, the
quotient and remainder.
You can store the result as a tuple:
>>> t = divmod(7, 3)
>>> print t
(2, 1)
7. What is dictionary in python? List out the operations and methods with example.
• Keys are unique within a dictionary while values may not be.
• The values of a dictionary can be of any type, but the keys must be of an immutable
data type such as strings, numbers, or tuples.
• Dictionary is one of the compound data type like strings, list and tuple. Every element
in a dictionary is the key-value pair.
• An empty dictionary without any items is written with just two curly braces, like this: {}.
17
Creating a Dictionary:
• A dictionary can be Created by specifying the key and value separated by colon(:) and
the elements are separated by comma (,).The entire set of elements must be enclosed by
curly braces {}.
Syntax: #To Create a Dictionary with Key-Value Pairs:
Dict={ }
Example:
#Keys-Value can have mixed datatype
Example:
>>Dict2={“Name”: “Zara”, “Subject”:[“Maths”, “Phy”, “Chemistry”],
“Marks”:[198,192,193], “Avg”:92}
>>Dict2[“Name”]
>>Dict2[“Avg”]
>>Dict2[“Subject”]
Output:
Zara
20.1
[“Maths”, “Phy”, “Chemistry”]
Example:
Example
>>> My_dict={'Name':'Nivetha','rank':5,'Average':78.9}
>>> My_dict['rank']=3
>>> My_dict
{'Name': 'abi', 'rank': 3, 'Average': 78.9}
DICTIONARY METHODS:
8 [Link](key, default=None) For key, returns value or default if key not in dictionary
dict.has_key(key)
9 Returns true if key in dictionary dict, false otherwise
DICTIONARY OPERATION:
Operation Description Input Function Output
Dict1={“Name”:”zara”,”Age”:14,”sex”:”M ”} Cmp(dict1,di 1
Compares
cmp(dict1, Dict2={“Name”:”zara”,”Age”:14} ct2) 0
dict2) elements of both
Dict3={“Name”:”zara”,”Age”:14} Cmp(dict2,d
dict.
ict3)
len(dict) Gives the total Dict1={“Name”:”zara”,”Age”:14,”sex”:”M ”} Len(dict1) 2
length of the Dict2={“Name”:”zara”,”Age”:14}
dictionary. Len(dict2) 3
The len function also works on dictionaries; it returns the number of key:value pairs:
>>>
len(dict1) 3
Where:
Expr(x) is an expression,usually but not always containing X.
Iterable is some [Link] itrable may be a sequence or an unordered collection a list,
string or tuple.
Example 1:
>>> a = [11,22,33,44]
>>> b =[x*2 for x in a]
>>>b
[22,44,66,88]
Example 2:
Given the following list of strings:
Names= [‘alice’, ‘ramesh’, ‘nitya’]
A list of all upper case Names
A List of Capitalized ( first letter upper case)
>>>[[Link]() for x in names]
[‘ALICE’, ‘RAMESH’, ‘NITA’]
>>>[[Link]() for x in names]
[‘Alice’ , ‘Ramesh’ , ‘Nita’]
20
Example 3:
>>> fish_tuple=('blowfish','clowfish','catfish','octopus')
>>> fish_list=[fish for fish in fish_tuple if fish != 'octopus']
>>> print(fish_list) ['blowfish', 'clowfish', 'catfish']
Example 4:
My_list=[]
for x in [20,40,60]:
for y in [2,4,6]:
My_list.append(x*y)
print (My_list)
Output: [40, 80, 120, 80, 160, 240, 120, 240, 360]
Note: This code multiplies the items in the first list (x) by the items in the second list (y) over
each iteration
Program For Example 4 using List Comprehension
My_list=[x*y for x in [20,40,60] for y in [2,4,6]]
print(My_list)
Output: [40, 80, 120, 80, 160, 240, 120, 240, 360]
List Comprehensions allows us to transform one list or other sequence into a new list. They
Provide a concise syntax for completing the task and limiting the lines of code.
Example 5:
#To create a simple
list x=[ i for i in range
(10)] print (x)
Output: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]