Python 2
Python 2
What are lists in Python and how are they used to store and manipulate a
collection of data?
Definition:
A list is a collection of items in Python.
It is ordered and changeable (mutable).
Lists are written inside square brackets [ ] and items are separated by commas.
---
Syntax:
list_name = [item1, item2, item3
Example:
fruits = ['apple', 'banana', 'mango'
Program Example:
Output:
Definition:
In Python, Augmented Assignment Operators are shorthand operators that combine arithmetic or
bitwise operations with assignment.
Example: x = x + 5 can be written as x += 5.
Syntax Format:
variable <augmented_operator> expression
Example: x += 3 is the same as x = x + 3.
List of Common Augmented Assignment Operators:
Example 1: Numbers
x = 10
x += 5
x *= 2
x -= 10
print(x)
Output:
20
Example 2: Strings
name = "Yash"
name += "wanth"
print(name)
Output:
Yashwanth
Example 3: Lists
mylist = [1, 2, 3]
mylist += [4, 5]
print(mylist)
Output:
[1, 2, 3, 4, 5]
Example:
Slicing: Slicing is used to extract a portion of the list. Syntax: list[start:stop] returns elements from
index start to stop-1.
Example:
Shortcut Slicing:
Conclusion: Negative indexing allows access to elements from the end of the list. Slicing helps
extract sublists using index ranges. Both features make list handling easier and more efficient.
Q4. Define list and explain different list methods like append(), sort(),
index(), insert(), remove(), and pop() with examples.
Definition: A list in Python is an ordered, mutable collection used to store multiple items. Lists are
defined using square brackets [ ], and elements are separated by commas.
Example:
numbers = [4, 1, 3, 2]
numbers.sort()
print(numbers) # Output: [1, 2, 3, 4]
6. pop(index) – Removes and returns element at given index. If index not given, removes last item.
Conclusion: Lists in Python are flexible and powerful. These methods allow us to efficiently add,
remove, sort, and access elements in a list.
import pprint
message = 'It was a bright cold day in April, and the clocks were striking thirteen.'
count = {}
for character in message:
count.setdefault(character, 0)
count[character] += 1
pprint.pprint(count)
Conclusion: pprint() is used to print large or nested dictionaries in a readable format. It is helpful for
debugging and clean output
frommath importsqrt
mylist= []
n= int(input("Enter the Number of Elements: "))
for i in range(n):
val= int(input("Enter the element:"))
mylist.append(val)
sum=0
for elem in mylist:
sum=sum+elem
mean = sum/n
print("Sum=",sum)
print("Mean=",mean)
variance = 0
for elem in mylist:
variance+= (elem-mean)*(elem-mean)
variance=variance/n
print("variance=",variance)
stddev= sqrt(variance)
print("Stddev=",stddev)
output:
Enter the Number of Elements: 3
Enter the element :15
Enter the element :10
Enter the element :10
Sum= 35
Mean= 11.666666666666666
variance= 5.5555555555555545
Stddev= 2.357022603955158
Sample Output 1:
Input: Pooka
Output: Pooka is my pet.
Sample Output 2:
Input: Tiger
Output: I do not have a pet named Tiger
Explanation: The list contains 3 pet names. The program takes user input and checks if the name
exists in the list using in. If found, it prints a confirmation. If not found, the else block runs.
Note: not in can be used to check if a value is missing from the list:
Conclusion: in and not in operators are useful for checking the presence or absence of values in a
list, and are commonly used in conditional statements.
8Q. How is tuple different from list? Which function is used to convert list to
tuple?
Definition:
A list is a mutable (changeable) sequence of values, whereas a tuple is an immutable (unchangeable)
sequence. Both can store multiple items, but only lists can be modified after creation
Difference between List and Tuple (as per Module):
myList = [1, 2, 3]
myTuple = (1, 2, 3)
Conversion Function:
To convert a list into a tuple, use the tuple() function.
Example:
myList = [1, 2, 3]
print(myList)
Output:
[1, 2, 3]
[100, 2, 3]
Explanation:
Conclusion:
Lists in Python are mutable. We can modify individual elements using indexing.
This property makes lists flexible and useful in dynamic programs.
In Python, data types are classified as mutable and immutable based on whether their values can be
changed after creation.
Definition:
Mutable data types can be modified after their creation. Elements can be added, removed, or
changed.
List
Dictionary
Set
myList = [1, 2, 3]
print(myList)
myList[0] = 100
print(myList)
Output:
[1, 2, 3]
[100, 2, 3]
Explanation:
The list element at index 0 was modified from 1 to 100.
This proves that lists are mutable, as their contents can be changed.
Definition:
Immutable data types cannot be changed after their creation.
Any operation that tries to change the value will result in a new object or an error.
Tuple
String
Integer
Float
myTuple = (1, 2, 3)
myTuple[0] = 100
Output:
Explanation:
Tuples do not allow item assignment. Any such operation results in an error.
This shows that tuples are immutable.
Conclusion:
1. random.choice()
Returns a random element from a list.
Syntax: random.choice(list_name)
import random
names = ['Alice', 'Bob', 'Charlie']
print(random.choice(names))
Output:
Any one name: Alice, Bob, or CharliE
2. random.shuffle()
Shuffles elements of a list randomly (modifies list in-place).
Syntax: random.shuffle(list_name)
Example (Module – Page 6):
import random
cards = ['A', 'K', 'Q', 'J']
random.shuffle(cards)
print(cards)
Output:
Random order like: ['J', 'Q', 'K', 'A']
Conclusion:
random.choice() → selects one random item
random.shuffle() → shuffles the full list randomly
➢ If the function modifies the list or dictionary that is passed, we may not want these
changes in the original list or dictionary value.
➢ For this, Python provides a module named copy that provides both the copy() and
deepcopy() functions.
➢ copy(), can be used to make a duplicate copy of a mutable value like a list or
dictionary, not just a copy of a reference.
➢ Now the spam and cheese variables refer to separate lists, which is why only the list
in cheese is modified when you assign 42 at index 1.
➢ The reference ID numbers are no longer the same for both variables because the
variables refer to independent lists
copy function
>>> import copy
>>> old_list = [[1, 1, 1], [2, 2, 2], [3, 3, 3]]
>>> new_list = copy.copy(old_list)
>>> old_list[1][0] = 'BB'
>>> print("Old list:", old_list)
>>> print("New list:", new_list)
>>> print(id(old_list))
>>> print(id(new_list))
Output:
Old list: [[1, 1, 1], ['BB', 2, 2], [3, 3, 3]]
New list: [[1, 1, 1], ['BB', 2, 2], [3, 3, 3]]
1498111334272
1498110961152
deepcopy() Function
>>> import copy
>>> old_list = [[1, 1, 1], [2, 2, 2], [3, 3, 3]]
>>> new_list = copy.deepcopy(old_list)
>>> old_list[1][0] = 'BB'
>>> print("Old list:", old_list)
>>> print("New list:", new_list)
>>> print(id(old_list))
>>> print(id(new_list))
Output
Old list: [[1, 1, 1], ['BB', 2, 2], [3, 3, 3]]
New list: [[1, 1, 1], [2, 2, 2], [3, 3, 3]]
1498111298880
1498111336064
Q13. Explain two ways to remove values from lists (as per
module).
1. Using del Statement
del list_name[index]
Example:
Syntax:
list_name.remove(value)
Example:
spam = ['a', 'b', 'a']
spam.remove('a')
print(spam) # Output: ['b', 'a']
> “The remove() method is passed the value to be removed from the list it is called on.”
“If the value appears multiple times, only the first instance will be removed.”
✅ Conclusion:
Use del when you know the index.
Use remove() when you know the value.
Q14. Explain the concept of List Concatenation and List Replication in detail.
1. List Concatenation using + Operator
🔹 Definition:
List concatenation is the process of joining two or more lists to create a single new list.
This is done using the + operator.
🔹 Key Points:
🔹 Syntax:
list3 = list1 + list2
🔹 Example:
list1 = [1, 2, 3]
list2 = [4, 5]
result = list1 + list2
print(result) # Output: [1, 2, 3, 4, 5]
> “The + operator can combine two lists to create a new list value in the same way it combines two
strings into a new string value.”
🔹 Definition:
List replication is the process of repeating the elements of a list multiple times using the * operator.
🔹 Key Points:
🔹 Syntax:
list2 = list1 * n
🔹 Example:
list1 = ['Hi']
result = list1 * 3
print(result) # Output: ['Hi', 'Hi', 'Hi']
> “The * operator can also be used with a list and an integer value to replicate the list.”
✅ Conclusion:
> Trying to access a key that does not exist in a dictionary will result in a KeyError
error message, much like a list’s “out-of-range” IndexError error message.
1. keys()
2. values()
3. items()
These methods return view objects, which act like lists and are commonly used in loops
🔹 1. keys() Method
Returns a view object that displays all the keys of the dictionary.
📌 Syntax:
dictionary.keys()
📌 Example:
📌 Output:
print(list(student.keys()))
Output:
> “The keys() method returns list-like values of the dictionary’s keys.”
🔹 2. values() Method
Returns a view object that contains all the values in the dictionary.
📌 Syntax:
dictionary.values()
📌 Example:
📌 Output:
print(list(student.values()))
📌 From module:
🔹 3. items() Method
📌 Definition:
Returns a view object that returns all (key, value) pairs as tuples.
📌 Syntax:
dictionary.items()
📌 Example:
📌 Output:
✅ Convert to list:
print(list(student.items()))
> “The values in the dict_items returned by items() are tuples of the key and value.”
✅ Using keys():
✅ Using values():
> “We can use the multiple assignment trick in a for loop to assign the key and value to separate
variables.”
Sample Output:
Final Dictionary:
{'name': 'Yash', 'age': '19', 'city': 'Bengaluru'}
18. Read a multi-digit number (as chars) from the console. Develop a program
to print the frequency
of each digit with suitable message.
num = input("Enter a number : ")
print("The number entered is:", num)
uniqDig = set(num)
for elem in uniqDig:
print(elem, "occurs", num.count(elem), "times")
output:
Enter a number : 11232
The number entered is: 11232
3 occurs 1 times
2 occurs 2 times
1 occurs 2 times
The first time setdefault() is called, the dictionary in spam changes to {'color': 'black', 'age': 5, 'name':
'Pooka'}. The method returns the value 'black' because this is now the value set for the key 'color'.
When spam.setdefault('color', 'white') is called next, the value for that key is not changed to 'white'
because spam already has a key named 'color'.
allGuests = {
'Alice': {'apples': 5, 'pretzels': 12},
'Bob': {'ham sandwiches': 3, 'apples': 2},
'Carol': {'cups': 3, 'apple pies': 1}
}
➢ Inside the totalBrought() function, the for loop iterates over the keyvalue pairs in
guests 1.
➢ Inside the loop, the string of the guest’s name is assigned to k, and the dictionary of
picnic items they’re bringing is assigned to v.
➢ If the item parameter exists as a key in this dictionary, it’s value (the quantity) is
added to numBrought 2.
➢ If it does not exist as a key, the get() method returns 0 to be added to numBrought
21. # Program to input 10 student records and print only the student
names
students = {}
for i in range(10):
name = input("Enter student name: ")
marks = int(input("Enter marks for " + name + ": "))
students[name] = marks
print("\nStudent Names:")
for student in students:
print(student)
Enter student name: Akash
Enter marks: 85
Enter student name: Riya
Enter marks: 90
Enter student name: Vivek
Enter marks: 88
Enter student name: Neha
Enter marks: 92
Enter student name: Rahul
Enter marks: 77
Enter student name: Sneha
Enter marks: 84
Enter student name: Deepa
Enter marks: 79
Enter student name: Arjun
Enter marks: 93
Enter student name: Kiran
Enter marks: 80
Enter student name: Divya
Enter marks: 86
Student Names:
Akash
Riya
Vivek
Neha
Rahul
Sneha
Deepa
Arjun
Kiran
Divya
Q22. Q. Explain List Methods in Python: Adding, Removing, Finding, Sorting, Reversing (With
Examples
🔹 1. Adding Elements
l = [1, 2, 3]
l.append(4)
print(l)
# Output: [1, 2, 3, 4]
b) insert(index, value) – Inserts at specific index
🔹 2. Removing Elements
🔹 3. Finding Elements
🔹 4. Sorting List
l = [9, 2, 5, 1]
l.sort()
print(l)
# Output: [1, 2, 5, 9]
🔹 5. Reversing List
a) reverse() – Reverses the list order
l = [1, 2, 3, 4]
l.reverse()
print(l)
# Output: [4, 3, 2, 1]
🔚 Conclusion
List methods are used to add, delete, find, sort and reverse data in a collection. These are essential
operations covered in Module 2 and commonly used in all Python programs.