0% found this document useful (0 votes)
7 views28 pages

Python Dictionary Operations Guide

The document provides an overview of Python dictionaries, including their syntax, how to access, update, add, and delete elements. It also covers various sorting algorithms such as Insertion Sort, Selection Sort, and Merge Sort, along with illustrative examples and code snippets. Additionally, it discusses creating histograms and concepts like list aliasing, cloning, and deleting list elements.

Uploaded by

Balaji Sri Kumar
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views28 pages

Python Dictionary Operations Guide

The document provides an overview of Python dictionaries, including their syntax, how to access, update, add, and delete elements. It also covers various sorting algorithms such as Insertion Sort, Selection Sort, and Merge Sort, along with illustrative examples and code snippets. Additionally, it discusses creating histograms and concepts like list aliasing, cloning, and deleting list elements.

Uploaded by

Balaji Sri Kumar
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

[Link] Problem Solving and Python Programming [Link]

in/
4.3 DICTIONARIES
Dictionaries is an unordered collection of items. Dictionaries are a kind of hash
table. The value of a dictionary can be accessed by a key. Dictionaries are enclosed by
curly braces ‘{ }’ and values can be accessed using square braces ‘[ ]’

/
in
Syntax:

n.
dict_name= {key: value}

aa
A Key can be any Immutable type like String, Number, Tuple. A value can be any
datatype.

iy
The values can be repeated and the keys should not be repeated.

or
Ex:
>>>dict1={}
>>>dict2={1:10,2:20,3:30} .p
w
>>>dict3={‘A’:’apple’,’B’:’200’}
w
>>>dict4={(1,2,3):’A’,(4,5):’B’}
>>>dict5={[1,2,3]:’A’,[4,5]:’B’} #Error, Only Immutable types can be assigned in Keys
// w
s:

4.3.1 ACCESS, UPDATE, ADD, DELETE ELEMENTS IN DICTIONARY:


Accessing Values in Dictionary
tp

To access dictionary elements, you can use the familiar square brackets along
ht

with the key to obtain its value.


Ex:
>>>d={‘name’:’xyz’,’age’:23}
>>>d[‘name’] ’xyz’ # since ’name’ is a String datatype, it should be represented within
quotes
>>>d[name]  shows
error By get()method
>>>[Link](‘name’)  ‘xyz’

Update Values in Dictionary: You can update a dictionary by adding a new entry or a
key-value pair, modifying an existing entry.
[Link] [Link]
Ex:
>>> d={‘name’:’xyz’,’age’:23}
>>>print(d)  {‘ name’:’xyz’,’age’:23}
>>>d[‘age’=24] #modifying existing element

/
>>>print(d)  {‘ name’:’xyz’,’age’:23}

in
By update method

n.
>>>d1={‘place’:’abc’}

aa
>>>[Link](d1)
print(d)  {‘place’:’abc’,‘ name’:’xyz’,’age’:23}

iy
or
Adding Values in Dictionary
>>>d[‘gender’]=’m’ #Adding new entry
.p
>>> print(d)  {‘gender’:’m’, ‘place’:’abc’,‘ name’:’xyz’,’age’:23}
w
w

Deleting or Removing Values in Dictionary


w

You can either remove individual dictionary elements or clear the entire contents
//

of a dictionary.
s:

>>>del d[‘name’] {‘gender’:’m’, ‘place’:’abc’,’age’:23}


tp

>>>[Link]() # remove all entries in dictionary


>>>del d #delete entire dictionary
ht
[Link] [Link]
ILLUSTRATIVE EXAMPLES
Note- Always get an Input from the USER.
[Link] a Python Program to find Largest, Smallest, Second Largest, Second
Smallest in a List without using min() & max() function.

/
in
>>>def find_len(list1):
length =

n.
len(list1)

aa
[Link]()
print ("Largest element is:", list1[length-

iy
1]) print ("Smallest element is:", list1[0])

or
print ("Second Largest element is:",

.p
list1[length-2]) print ("Second Smallest
element is:", list1[1])
w
>>>list1=[12, 45, 2, 41, 31, 10, 8, 6, 4]
w

>>>Largest = find_len(list1)
w

Output:
//

Largest element is:


s:

45 Smallest
tp

element is: 2
Second Largest element is:
ht

41 Second Smallest
element is: 4

2. Find the output of the following program


Program 2.1:
>>>subject= ['Physics', 'Chemistry', 'Computer']
>>>mark=[98,87,94]
>>>empty=[]
>>> print(subject, mark, empty)
Output:
['Physics', 'Chemistry', 'Computer'], [98, 87, 94], []
[Link] [Link]
Program 2.2:
>>>mark=[98,87,94]
>>> mark[2]=100
>>> print(mark)

/
in
Output:
[98, 87, 100]

n.
aa
Program 2.3:
>>> subject= ['Physics', 'Chemistry', 'Computer']

iy
>>> 'Chemistry' in subject

or
Output:
True
.p
w
Program 2.4:
w

>>> subject= ['Physics', 'Chemistry', 'Computer']


//w

>>> for s in subject:


print(s)
s:

Output:
tp

Physics
Chemistr
ht

y
Compute
r

Program 2.5:
>>> for i in
range(len(mark)):
mark[i] = mark[i] * 2
>>> print(mark)

Output:
[Link] [Link]
INSERTION SORT
This is an in-place comparison-based sorting algorithm. Here, a sub-list is
maintained which is always sorted. For example, the lower part of an array is
maintained to be sorted. An element which is to be 'inserted in this sorted sub-list, has

/
to find its appropriate place and then it has to be inserted there. Hence the name,

in
insertion sort.

n.
The array is searched sequentially and unsorted items are moved and inserted into the

aa
sorted sub-list (in the same array). This algorithm is not suitable for large data sets as
its average and worst case complexity are of Ο(n2), where n is the number of items.

iy
or
.p
w
w
// w
s:
tp
ht
[Link] [Link]
Program for Insertion sort
def insertionsort(a):
for index in
range(1,len(a):

/
currentvalue=a[i]

in
position=i

n.
while position>0 and a[position-

aa
1]>currentvalue: a[position]=a[position-1]
position=position-1

iy
a[position]=currentvalu

or
e
list=[50,60,40,30,20,70]
print( “Original list is:”,list) .p
w
insertionsort(list)
w
print(”List after insert:”,a)
//w

Output:
s:

Original list
is=[50,60,40,30,20,70] List
tp

afterinsert:[20,30.40,50,60,70]
ht
[Link] [Link]
2. SELECTION SORT
In the selection sort algorithm, an array is sorted by recursively finding the
minimum element from the unsorted part and inserting it at the beginning. Two
subarrays are formed during the execution of Selection sort on a given array.

/
 The subarray, which is already sorted

in
 The subarray, which is unsorted.

n.
During every iteration of selection sort, the minimum element from the unsorted subarray

aa
is popped and inserted into the sorted subarray.

iy
or
.p
w
w
//w
s:
tp
ht
[Link] [Link]
Program for Selection sort:
def selectionSort(alist):
for i in range(len(alist)-1,0,-
1): pos=0

/
for location in range(1,i+1):

in
if alist[location]>alist[pos]:

n.
pos= location

aa
temp = alist[i]
alist[i] =

iy
alist[pos]

or
alist[pos] =
temp
alist = [54,26,93,17,77,31,44,55,20] .p
w
selectionSort(alis
w
t) print(a list)
w
://

Output:
[17, 20, 26, 31, 44, 54, 55, 77, 93]
s
tp

3. MERGE SORT
ht

Merge sort is a sorting technique based on divide and conquer technique. With
worst- case time complexity being Ο(n log n), it is one of the most respected algorithms.
Merge sort first divides the array into equal halves and then combines them in a sorted
manner.
[Link] [Link]

/
in
n.
aa
iy
or
.p
w
w
// w
s:
tp

Program for Merge sort


def mergeSort(alist):
ht

print("Splitting
",alist) if
len(alist)>1:
mid = len(alist)//2
lefthalf = alist[:mid]
righthalf =
alist[mid:]
mergeSort(lefthalf)
mergeSort(righthalf
) i=0
j=0
k=
0
[Link] [Link]
while i < len(lefthalf) and j <
len(righthalf): if lefthalf[i] < righthalf[j]:
alist[k]=lefthalf[i
] i=i+1

/
else:

in
alist[k]=righthalf[j

n.
] j=j+1

aa
k=k+1
while i <

iy
len(lefthalf):

or
alist[k]=lefthalf[i]
i=i+1
k=k+1 .p
w
while j <
w

len(righthalf):
w

alist[k]=righthalf[j]
//

j=j+1
s:

k=k+1
print("Merging
tp

",alist)
ht

alist = [50, 60, 40, 20, 70, 100]]


mergeSort(alis
t) print(alist)
Output:
Original list is: [50, 60, 40, 20, 70, 100]
Sorted list is: [20, 40, 50, 60, 70, 100]
[Link] [Link]
HISTOGRAM
To create a histogram, the first step is to create bin of the ranges, then distribute
the whole range of the values into a series of intervals, and the count the values which
fall into each of the intervals. Bins are clearly identified as consecutive, non-overlapping

/
intervals of variables. Program:

in
def histogram(items):

n.
for n in items:

aa
output=’’
times=n

iy
while (times>0):

or
output+=’*’
times=times-1
.p
print(output)
w
histogram([2,3,4,3,
w
2])
//w

Output
:
s:

**
***
tp

****
ht

***
**

Example :2

import [Link] as
plt import numpy as np
from matplotlib import
colors from [Link]
import PercentFormatter
[Link] [Link]

# Creating dataset
[Link](236857
52)
N_points = 10000

/
in
n_bins = 20

n.
# Creating distribution
x = [Link](N_points)

aa
y = .8 ** x + [Link](10000) +

iy
25 # Creating histogram
fig, axs = [Link](1,

or
1, figsize =(10, 7),
tight_layout = True) .p
w
[Link](x, bins =
n_bins) # Show plot
w

[Link]()
//w
s:
tp
ht
[Link] [Link]
Output :

/
in
n.
aa
iy
or
.p
w
w
// w
s:
tp
ht
[Link] [Link]
4.1.6 LIST ALIASING:
Since variables refer to objects, if we assign one variable to another, both
variables refer to same objects.(One or more variable can refer the same object)
>>>a=[1,2,3]

/
in
>>>b=a
>>>a is b # Displays True

n.
aa
4.1.7 LIST CLONING:
If we want to modify a list and also keep copy of the original we can use cloning

iy
to copy the list and make that as a reference.

or
Ex:
a=[1,2,3]
b=a[:]
.p
w
print(b)  [1,2,3]
w
w

4.1.8 LIST PARAMETER:


//

Passing a list as an argument actually passes a reference to the list, not the
s:

copy of the list. We can also pass a list as an argument to the function.
tp

Ex:
ht

>>> def mul(a_list): #a_list is a list passing as a parameter


for index,value in
enumerate(a_list):
a_list[index]=2*value
print(a_list)
>>> a_list=[1,2,3,4,5]
>>> mul(a_list)
Output:
[2, 4, 6, 8, 10]
[Link] [Link]
4.1.9 DELETING LIST ELEMENTS
To remove a list element, del operator can be used if an element to
be deleted is known. In the following code, the element ‘Chennai’ is deleted
by mentioning its index in the del operator.

/
in
Ex
:

n.
stulist = [‘Rama’, ‘Chennai’,
2018, ‘CSE’, 92.7] print ‘Initial

aa
list is : ‘, stulist

iy
del stulist[1]

or
print ‘Now the list is : ‘, stulist
Output:
.p
Initial list is : [‘Rama’, ‘Chennai’,
w
2018, ‘CSE’, 92.7] Now the list is :
w

[‘Rama’,
w

2018, ‘CSE’, 92.7]


//

pop() and remove() methods can also be used to delete list elements
s:
tp
ht
[Link] [Link]
4.1.4 LIST LOOP:
A loop is to access all the elements in a list.
>>> a=[‘apple’,’mango’,’lime’,’orange’]
>>> print(a) → [‘apple’,’mango’,’lime’,’orange’] # displays all at a time

/
>>> print(a[0]) → ‘apple’

in
n.
i) Method 1:

aa
for var in a:
print(a) #displays all at a time

iy
Output:

or
The loop goes on 4 times and print all
values ‘apple’,’mango’,’lime’,’orange’
‘apple’,’mango’,’lime’,’orange’
.p
w
‘apple’,’mango’,’lime’,’orange’
w

‘apple’,’mango’,’lime’,’orange’
//w

ii) Method 2:
s:

for var in a:
tp

print(var) #displays a item at a time


Output:
ht

The loop goes on 4 times and print items one by one.


‘apple’
’mango
’ ‘lime’
’orange’

iii) Method 3
>>>i=0
>>> for var in a:
[Link] [Link]
print(“I like”,a[i])
i=i+
1
Output:

/
The value of i makes the loop to goes on 4 times and print items one by one.

in
‘apple’

n.
’mango
’ ‘lime’

aa
’orange’

iy
or
1. Write a python program to print the items in the list using while loop.
>>>a=[‘apple’,’mango’,’lime’,’orange’]
>>>i=0 .p
w
>>>while len(a)>i:
w
print(“I like”,a[i])
i=i+1
w

Output:
//

The value of i makes the loop to goes on 4 times and print items one by one.
s:

‘apple’
tp

’mango
ht

’ ‘lime’
’orange’

4.1.5 LIST ARE MUTABLE:


Unlike String, List is mutable (changeable) which means we can change the
elements at any point.
Ex:
>>>a=[‘apple’,’mango’,’lime’,’orange’]
>>>a[0]=’grape’
>>>print(a) → ’grape’, ’mango’,’lime’,’orange’
[Link] [Link]

4.1.1 LIST OPERATIONS:

1. + Operator which concatenates two lists.


>>>list2=[1,2,3,4,5,6,7,8]

/
>>>list3=[‘Hello’,3.5,’abc’,4]

in
>>>print(list2+list3)

n.
Output

aa
1,2,3,4,5,6,7,8, ‘Hello’,3.5,’abc’,4

iy
2. * Operator multiples the list to the specific numbers

or
>>>list2=[1,2,3,4,5,6,7,8]
>>>list2*2
Output .p
w
1,2,3,4,5,6,7,8,1,2,3,4,5,6,7,8
w
w

4.1.2 LIST SLICE


A subsequence of a sequence is called a slice and the operation that extracts a
//

subsequence is called slicing. For slicing we use square brackets [ ]. Two integer values
s:

splitted by ( : ).
tp

Syntax:
ht

List_Name[Starting_Value : Ending_Value]
Ex
:
>>>a=[‘a’,’b’,’c’,’d’,’e’]
List a= ‘a’ ‘b’ ‘c’ ‘d’ ‘e’
Index from Left 0 1 2 3 4
Index from Right -5 -4 -3 -2 -1

>>> print(a[:])  ['a', 'b', 'c', 'd', 'e'] #Prints ALL


>>> print(a[1:])  ['b', 'c', 'd', 'e'] #Print from 1st Position to Last Position
>>> print(a[1:3])  ['b', 'c'] #Print from 1st Position to Last – 1 Position
[Link] [Link]
>>> print(a[:-1])  ['a', 'b', 'c', 'd'] #Print from Backwards except -1th Position
>>> print(a[1:-1])  ['b', 'c', 'd'] #Print from 1st Position till -1th Position

4.1.3 LIST METHODS (or) TYPES OF FUNCTIONS IN LIST

/
in
Consider the values of list a and list b be
>>>a=[‘apple’,’mango’,’lime’]

n.
>>>b=[‘grape’]

aa
[Link] Name Synta Description Example

iy
x
[Link](‘orange’

or
1. append() [Link]() The method append() will
)
add the item to the end of a
.plist
w
2. insert() [Link](index, This method inserts an item [Link](1,’banana
’)
w
it em) at a particular place and
w

two arguments (index,item)


//

3. extend() [Link](item This method is used to [Link](‘grape


s:

1
combine two list with the ’) (or)
,item2)
tp

items in the argument. [Link](b)


ht

4. remove() [Link](item This method will remove [Link](’apple’)


)
an item in the list.

5. pop() [Link](index) This method returns the [Link](1)


item by the index position >>>mango
and removes it.

6. index() [Link](item) This method will return [Link](‘lime’)


index value of list and >>>2
takes index value as
argument.
7. copy() dest_list=listname.c This method is used to c=[Link]()
op y() copy a list to another list.
[Link] [Link]
8. reverse() [Link]() This method is used to [Link]()
reverse the items in a list.

9. count() [Link](item) This method is used to [Link](‘lime’)


count the duplicate items >>>1

/
in
in the list which takes the
item as arguments.

n.
10. sort() [Link]() This method is used to [Link]()

aa
arrange the list from >>>a=[‘apple’,
ascending to descending ‘lime’, ‘mango’]

iy
alphabetically.

or
11. clear() [Link]() This method is used to clear [Link]() -->[]

.p all the values in the list.


w
w
// w
s:
tp
ht
[Link] [Link]
4.3.2 METHODS ON DICTIONARIES:
Consider the value of Dictionary d and d1 as
follows: d={‘a’:1,’b’:2,’c’:3,’d’:4}
d1={‘e’:5,’f’:6}

/
S.N Name Synta Description Example

in
o x

n.
1. len() len(dictonary) Gives the total length len(d)  4
of the dictionary.

aa
2. keys() [Link]() Return the >>> [Link]()

iy
dictionary's keys. ['a', 'c', 'b',

or
'd']
3. values() [Link]() Return the >>>
.p dictionary's Values [Link]()
w
[1, 3, 2, 4]
w

4. items() [Link]() Return the >>> [Link]()


w

dictionary's Keys [('a', 1), ('c', 3),


('b',
//

and Values
2), ('d', 4)]
s:

5. key in dict key in dict Returns True if the Key >>> 'a' in
tp

is in Dictionary, else d True


ht

returns false.

6. key not key not in dict Returns True if the >>> 'e' not in
in dict Key is not in d True
Dictionary, else
returns false.
7. has_ke dictionary.has_key(key Checks whether the >>>
)
y (key) dictionary has the d.has_key('a')
specified key. True

8. get() [Link](key) Get the value and >>>


Return the value of [Link]('b') 2
key.
[Link] [Link]
9. update() Dest_dictionary.update Update the dictionary >>>[Link](d1)
( Source_dict) with the key from existing >>> print(d)
keys. {'a': 1, 'c': 3, 'b': 2,
'e': 5, 'd': 4, 'f': 6}

/
10. cmp() cmp(dictionary1, Compares elements of >>>

in
dictionary2) both dictionary. Returns cmp(d,d1) 1

n.
0 if the elements are

aa
same, Else returns 1.
11 copy() new_dict = Return a copy of >>> d2=[Link]()

iy
original_dict.copy( the dictionary. >>> print(d2)

or
) {'e': 5, 'f': 6}
12. pop()
.p
[Link](‘key’) Remove the item with
key and return its value
>>> [Link]('f')
6
w
13. popitems( [Link]() Remove and return an >>>
w

) item with its key and [Link]() ('a',


w

value. 1)
//

14. clear() [Link]() Remove all items form [Link]()


s:

the dictionary.
tp
ht

4.4 LIST COMPREHENSION:


List comprehension is an elegant way to define and create list in Python. These
lists have often the qualities of sets. It consists of brackets containing an expression
followed by a for clause, then zero or more for or if clauses.
Ex-1:
>>>x = [i for i in range(10)]
>>>print x
Output:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[Link] [Link]
Ex-2:
>>>squares = []
>>>for x in range(10):
[Link](x**

/
2) print (squares)

in
>>>squares = [x**2 for x in range(10)] # List comprehensions to get the same result:

n.
>>>print (squares)

aa
Output:

iy
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

or
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

.p
w
w
//w
s:
tp
ht
[Link] [Link]
4.2 TUPLE
Tuples are sequence of values much like the list. The values stored in the tuple
can be of any type and they are indexed by integers.
The main difference between list and tuple is Tuple is immutable. Tuple is represented

/
using ‘( )’

in
Syntax:

n.
tuple_name=(items)

aa
Ex:

iy
>>> tuple1=(‘1’,’2’,’3’,’5’)

or
>>>tuple2=(‘a’,’b’,’c’)
>>>tuple3=’3’,’apple’,’100’
.p
w
TUPLES ARE IMMUTABLE:
w
The values of tuple cannot be changed.
>>> tuple1=(‘1’,’2’,’3’,’5’)
w

tuple1[1]=’4’ #It Shows Error


//

Tuples can be immutable but if you want to add an item we can add it by
s:

t1=(‘a’,’b’)
tp

t1=(‘A’,)+t1[1:]  t1=(‘A’,’b)
ht

The disadvantage in this method is we can only add the items from the beginning.

4.2.1 TUPLE ASSIGNMENT


Tuple Assignment means assigning a tuple value into another tuple.
Ex:
t=(‘Hello’,’hi’)
>>>m,n=t
>>>print(m)  Hello
>>>print(n)  hi
>>>print(t)  Hello,hi
[Link] [Link]
In order to interchange the values of the two tuples The following method is used.
>>>a=(‘1’,’4’)
>>>b=(‘10’,’15’)
>>>a,b=b,a

/
in
>>>print(a,b)
((‘10’,’15’), (‘1’,’4’))

n.
aa
COMPARING TUPLES
The comparison operator works with tuple and other sequence. It will check the

iy
elements of one tuple to another tuple. If they are equal it return true. If they are not equal

or
it returns false.
>>>t1=(‘1’,’2’,’3’,’4’,’5’)
>>>t2=(‘a’,’b’,’c’)
.p
w
>>>t1<t2 #It returns false
w
w

4.2.2 TUPLE AS RETURN VALUE


//

In a function a tuple can return multiple values where a normal function can return
s:

single value at a time.


tp

Example-1:
ht

Using a built-in function divmod which return quotient and remainder at the same time.
>>>t=divmod(7,3)
>>>print(t)  (2,1)
>>>quot,rem=divmod(7,3)
>>>print(quot)  2
>>>print(rem) 1
Example-2:
def swap(a,b,c):
return(c,b,a)
a=100
[Link] [Link]
b=20
0
c=30
0

/
>>>print(“Before Swapping”,a,b,c)

in
>>>print(“After Swapping”,swap(a,b,c))

n.
Output:

aa
Before Swapping 100,200,300
After Swapping 300,200,100

iy
or
.p
w
w
// w
s:
tp
ht
Problem Solving and Python Programming (GE3151) – Reg 2021
Unit I: Computational Thinking and Problem Solving
Computational Thinking and Problem Solving | Fundamentals of Computing | Identification of Computational Problems |
Algorithms | Building Blocks | Notation | Algorithmic Problem Solving | Simple Strategies for Developing Algorithms |
Illustrative Problems | Anna University Two Marks Questions & Answers | Multiple Choice Questions and Answers

Unit II: Data Types, Expressions, Statements


Data Types, Expressions, Statements | Introduction to Python | How to Write and Execute Python Program | Concept
of Interpreter and Compiler | Python Interpreter | Interactive and Script Modes | Debugging | Values and Types |
Variables, Expressions and Statements | Tuple Assignment | Indentation, String Operations | Functions | Illustrative
Programs | Anna University Two Marks Questions & Answers | Multiple Choice Questions

Unit III: Control Flow, Functions, Strings


Control Flow, Functions, Strings | Boolean Values | Operators | Input and Output | Conditional Statements | Iteration
| Fruitful Functions | Recursion | Strings | Lists as arrays | Illustrative Programs | Anna University Two Marks
Questions & Answers | Multiple Choice Questions

Unit IV: Lists, Tuples, Dictionaries


Lists, Tuples, Dictionaries | Lists | Tuples | Dictionaries | Advanced List Processing - List Comprehension | Illustrative
Programs | Anna University Two Marks Questions & Answers | Multiple Choice Questions

Unit V: Files, Modules, Packages


Files, Modules, Packages | Files | Command Line Arguments | Errors and Exceptions | Modules | Packages | Two Marks
Questions with Answers | Multiple Choice Questions

Common to all 1st Semester

HOME | EEE | ECE | MECH | CIVIL | CSE


1st Semester Anna University EEE- Reg 2021
Professional English – I
2nd Semester 3rd Semester
Matrices and Calculus
Probability and Complex
Professional English - II Functions
Engineering Physics
Statistics and Numerical Electromagnetic Fields
Engineering Chemistry Methods
Problem Solving and Physics for Electrical Digital Logic Circuits
Python Programming Engineering
Electron Devices and
Physics and Chemistry Basic Civil and Mechanical Circuits
Laboratory Engineering
Electrical Machines - I
Engineering Graphics
C Programming and Data
4th Semester Electric Circuit Analysis Structures
Environmental Sciences
and Sustainability 6th Semester
Transmission and 5th Semester
Distribution Protection and
Linear Integrated Power System Analysis Switchgear
Circuits
Power Electronics Power System
Measurements and Operation and Control
Instrumentation Control Systems
Open Elective – I
Microprocessor and
Microcontroller Professional Elective I
Professional Elective IV
Electrical Machines - II Professional Elective II
Professional Elective V
Professional Elective III
7th Semester Professional Elective VI
High Voltage Mandatory Course-I& Mandatory Course-
Engineering II& MC
Human Values and 8th Semester
Ethics
Elective –
Management Project Work /
Internship
Open Elective – II
Open Elective – III
Open Elective – IV
Professional Elective
VII Click on Clouds to navigate other department

[Link]

Common questions

Powered by AI

List mutability allows elements to be dynamically added, modified, or removed, which necessitates memory allocation and deallocation during these operations, potentially leading to fragmentation and increased memory use . As lists are mutable, memory overhead can also occur due to resizing when elements are appended. In contrast, tuples, being immutable, have a fixed size, leading to more predictable and efficient memory usage, especially when used as keys in dictionaries . Tuples, due to immutability, can improve performance in operations where their fixed-state guarantees are valuable, like iteration over large datasets where a stable reference is required .

When passing a list as a parameter in Python, you are passing a reference to the original list, not a copy. Any modifications to the list inside the function will reflect the original list, leading to potential side effects if functions alter lists unintentionally . To mitigate undesired changes, you can clone the list by creating a new list copy within the function, altering this copy instead of the original, using slicing or the copy method .

Method chaining allows multiple methods to be called on a dictionary in a single line by executing one method, then directly applying another to the result if applicable, enhancing readability and conciseness. However, not all methods return the dictionary object itself; for example, pop() returns the removed item. Practical use depends on ensuring subsequent methods expect outputs of earlier methods . Misuse can lead to runtime errors if chained methods are incompatible or if changes in the dictionary invalidate subsequent operations .

List comprehensions provide a syntax that is not only more concise but also faster than traditional loops for creating lists. They enable the generation of lists by specifying an expression followed by a for clause, and optionally more for or if clauses, resulting in very readable and writable code. This method reduces the need for the explicit invocation of append methods and typically results in shorter, clearer code that is executed more efficiently .

In Python, a tuple is an immutable sequence type, meaning once a tuple is created, its elements cannot be altered, added, or removed. This immutability makes tuples useful for fixed, unordered collections of items, reliable as keys in dictionaries, or for returning multiple values from a function confidently that their contents will not change . However, this means you cannot append, remove, or change elements directly within a tuple, unlike lists, which are mutable .

Both list comprehensions and loops can iterate over sequences to create lists, performing transformations specified by expressions. However, list comprehensions offer compact syntax designed for simple construct needs, improving code brevity and speed for many operations by reducing overhead of method calls or function definitions seen with traditional loops . They differ significantly in clarity of complex logic, where loops may provide more explicit, debuggable, iterative steps, especially in nested structures or conditional components requiring detailed elaboration .

List aliasing occurs when two different variables point to the same memory location that stores the list. When you assign one list to another using the assignment operator, no new list is created, and both variables refer to the same list object; thus, changing the list through one variable reflects it in the other . In contrast, list cloning involves creating a new copy of the list. This is typically achieved using slicing, where you create a new list with copied elements, thus preserving the original list. Any modifications to the cloned list do not affect the original list .

List slicing in Python allows for concise and readable code by enabling operations on sublists rather than manually iterating over index ranges. It provides a way to extract, modify, or copy portions of lists in a single, intuitive operation, which enhances both readability and performance . Slicing avoids verbose loops, prevents index-related errors, and facilitates clear intent, indicating with just a slice what part of a list is targeted for manipulation, while maintaining performance benefits with negligible overhead .

The pop() method removes an element at a specified index and returns it, allowing you to capture the removed item for further use. If no index is specified, it removes the last element by default . Unlike remove(), which deletes the first occurrence of the specified value but does not return it, leaving it up to you to search for the value in the list. Pop is useful when the position of the element is known, while remove is useful to delete specific known values without needing to find their index first .

Tuple assignment allows for multiple variables to be assigned at once, using tuple unpacking to distribute values from a tuple to variables simultaneously. This feature simplifies exchanging variable values without using temporary variables and enhances code readability, especially when expecting multiple return values from a function . For instance, "a, b = b, a" swaps the values of a and b directly and concisely without extra steps like storing values in temporary storage .

You might also like