0% found this document useful (0 votes)
3 views29 pages

تلخيص List + File

The document explains the use of the open() function in Python for file handling, detailing its parameters such as filename and mode. It covers various modes like 'r' for reading and 'w' for writing, along with examples of reading file contents, handling exceptions, and performing operations on file data. Additionally, it includes exercises and multiple-choice questions to reinforce understanding of file operations in Python.

Uploaded by

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

تلخيص List + File

The document explains the use of the open() function in Python for file handling, detailing its parameters such as filename and mode. It covers various modes like 'r' for reading and 'w' for writing, along with examples of reading file contents, handling exceptions, and performing operations on file data. Additionally, it includes exercises and multiple-choice questions to reinforce understanding of file operations in Python.

Uploaded by

Yosra Yaseen
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 29

Files

In Python, the open() function is used to open a file and return a file object. This file object
allows you to read, write, or manipulate the file contents.

fhand = open('mbox.txt', 'r')

Returns a handle open() returns a “file filename is a string Mode is optional and should
use to manipulate handle” - a variable be 'r' if we are planning to
the file used to perform read the file and 'w' if we are
operations on the file going to write to the file

Parameters
1. filename: A string that represents the name of the file to be opened. This can include a
relative or absolute path.
2. mode: A string that specifies the mode in which the file is opened. Some common
modes include:
o 'r': Read mode (default) - Opens the file for reading.
o 'w': Write mode - Opens the file for writing (overwrites the file if it exists).
# Open a file for reading # Open a file for writing

file = open('example.txt', 'r') file = open('example.txt', 'w')

…. file.write('Hello, World!')

…… file.close()

file.close()

# Handling File Not Found


try:
file = open('nonexistent.txt', 'r')
except FileNotFoundError:
print("File not found!") Ouput

``
Output
File test.txt contents:‫افرض ان لديك الملف التالي ويحتوي المبف على ما يلي‬

Python is a general-purpose, high-level.


Python was developed by Guido Van Rossum in 1989.

Making it easy to understand. Therefore, Python is recommended as the first programming language.
I love Python

‫ على محتوى الملف‬output ‫يعتمد كل‬

Code Output
fhand = open('test.txt') <_io.TextIOWrapper ‫الحالة االفتراضيه لفتح‬
print(fhand) name='mbox.txt' ‫الملف هي القراءة‬
mode='r'
encoding='UTF-8'>

fhand = open(test.txt',’w’) <_io.TextIOWrapper


print(fhand) name='mbox.txt'
mode='w'
encoding='UTF-8'>

file1 = open("mbox.txt", "r") Python is a general- ‫طباعة محتوى الملف‬


print(file1.read()) purpose, high-level. ‫كامال‬
Python was developed
by Guido Van Rossum in
1989.

Making it easy to
understand. Therefore,
Python is recommended
as the first programming
language.
I love Python
file1 = open("mbox.txt", "r") Python is a general- ‫طباعه اول سطر من‬
print(file1.readline()) purpose, high-level. ‫الملف‬

``
file1 = open("mbox.txt", "r") Python is ‫البدأ في المبف من‬
print(file1.read(9)) ‫البداية حتى الحرف‬
‫التاسع‬
file1 = open("mbox.txt", "r") a general-purpose, high- Seek(10)
file1.seek(10) level. ‫تعني البدأ في الملف‬
print(file1.read()) Python was developed ‫ابتداءا من الحرف‬
by Guido Van Rossum in ‫العاشر‬
1989.

Making it easy to
understand. Therefore,
Python is recommended
as the first programming
language.
I love Python
file1 = open("mbox.txt", "r") a gener ‫البدأ من الحرف العاشر‬
file1.seek(10) ‫ومن ثم اخذ سبع‬
print(file1.read(7)) ‫حروف فقط ابتداءا من‬
‫الحرف العاشر‬
fhand = open('mbox.txt') Line Count: 5 ‫عدد االسطر داخل‬
count = 0 ‫الملف‬
for line in fhand: ‫يتم حساب السطر‬
count = count + 1 ‫الفارغ‬
print('Line Count:', count)

fhand = open('mbox.txt') 217 ‫عدد االحرف داخل‬


inp = fhand.read() ‫الملف‬
print(len(inp))

fhand = open('mbox.txt') Python is a general- ‫طباعة كل االسطر التي‬


for line in fhand: purpose, high-level. Python ‫تبتدأ بكلمة‬
if line.startswith('Python') :
print(line) Python was developed
by Guido Van Rossum in
1989.
fhand = open('mbox.txt') There were 2 Python ‫عدد االسطر التي تبتدأ‬
count = 0 lines Python ‫بكلمة‬
for line in fhand:
if line.startswith('Python') :
count = count + 1
print('There were', count, 'Python lines')

``
There were 4 Python
Words ‫ في‬Python ‫عدد كلمات‬
fhand = open('mbox.txt') ‫الملف‬
count = 0
for line in fhand:
if 'Python' in line:
count = count + 1
print('There were', count, 'Python Words')
OUTPUT 2
file1 = open("file1.txt", "w") Output of Read function ‫ تعني سطر جديد‬n\
L = "This is Amman\n", "This is Paris\n", "This is is L = "This is Amman\n",
London\n" Hello "This is Paris\n", "This
This is Amman "is London\n
file1.write("Hello \n") This is Paris
file1.writelines(L) This is London
file1.close()
file1 = open("file1.txt", "r") Output of Readline
print("Output of Read function is ") function is
print(file1.read()) Hello
print()
file1 = open("mbox1.txt", "r")
print("Output of Read function is ") Output of Read(9)
print(file1.read()) function is
print() Hello
file1.seek(0) Th
print("Output of Readline function is ")
print(file1.readline()) Output of Readline(9)
print() function is
file1.seek(0) Hello
print("Output of Read(9) function is ")
print(file1.read(9))
print()
file1.seek(0)
print("Output of Readline(9) function is ")
print(file1.readline(9))

``
Multiple Choice
1. What is the default mode of the open() function?
a) 'r' ✔
b) 'w'
c) 'a'
d) 'rb'
2. What does the 'w' mode do in the open() function?
a) Opens a file for reading only
b) Opens a file for writing and truncates it ✔
c) Appends data to a file
d) Reads the file in binary mode
3. What happens if you try to open a non-existent file in 'r' mode?
a) Creates the file
b) Returns None
c) Raises a FileNotFoundError ✔
d) Opens an empty file
4. What function is used to open a file in Python?
a) file.open()
b) open() ✔
c) read_file()
d) file()

5. What does the open() function return?


a) A file handle ✔
b) The content of the file
c) The number of lines in the file
d) None of the above

``
6. Which mode should you use to read a file?
a) 'w'
b) 'r' ✔
c) 'rw'
d) 'x'
7. What character is used to represent a newline in strings?
a) \\
b) \n ✔
c) \t
d) \s
8. What happens if you try to open a file that does not exist?
a) The program ignores it.
b) It throws a FileNotFoundError. ✔
c) It creates a new file.
d) None of the above.

True or False
1. A file handle can be used to manipulate files.
True
Explanation: A file handle is an object returned by the open() function, which allows
operations like reading, writing, or appending to the file.
2. Using rstrip() removes whitespace and newline characters from the end of a string.
True
Explanation: The rstrip() method removes trailing whitespace and newline characters (\n)
from the end of a string.
3. The continue statement in a loop skips the current iteration and moves to the next.
True
Explanation: The continue statement allows the loop to skip the rest of the code for the
current iteration and move to the next iteration.
4. To iterate through each line of a file, you can use a for loop.
True

``
5. The input() function is used to prompt for a filename at runtime.
True

Writing Code
1. Write a python program that gets three names from the user and writes them to a file.

2.Write a python program that prompts the user for sales amounts and writes those amounts to the
sales.txt file.

``
3. Write a Python program that performs various tasks on a file entered by the user with
validation and exception handling, Tasks are :
a) Read file content.
b) Convert file contents to uppercase.
c) Count the occurrences of the letter 'I'.
d) Replace the word ‘Python’ with 'C#'.
e) Extract and print the substring 'C#'.
f) Extract and print line count

``
4. Write a Python program that will perform the following actions:
1. File Input: The program should first prompt the user to enter the name of the input text
file.
2. File Validation: Your program must check if the file exists. If the file does not exist, it
should print an informative error message and terminate gracefully.
3. Read and Process: If the file exists, read the contents of the file line by line.
String Manipulation Tasks (Apply to each line): For each line of text in the file, perform
these actions in the specified order:
4. Remove Leading/Trailing Whitespace: Remove any whitespace characters (spaces, tabs,
newlines) from the beginning and the end of the line.
5. Convert to Lowercase: Convert the entire line to lowercase.
6. Count Vowels: Calculate the number of vowels (‘a’, ‘e’, ‘I’, ‘o’, ‘u’) in the line.
7. Reverse the Line: Reverse the characters in the line.
8. Output: For each line processed, print the following, each on a new line:
o The original line as it was read from the file (before any processing).
o The processed line with whitespace removed and converted to lowercase.
o The vowel count for the processed line.
o The reversed version of the processed line.
9. Closing: Ensure that the file is properly closed after reading is complete.

``
5. Write a Python code that fulfills the requirement of taking multiple student marks, then saves the
maximum, minimum, and average marks to a file.

1. Function : calculate_and_save_marks(filename).
o Initialization: Initializes an empty list marks to store the marks entered by the
user.
o Input Loop:
 Uses a while True loop to continuously prompt the user to enter marks.
 Checks for the "done" input to end mark entry.
 Tries to convert input to a float to accept fractional marks. If a non-
number is entered, handles the ValueError exception
 Appends valid numbers to the marks list.
o Empty Mark List Check: After input is finished, verifies that at least one
mark was entered. If the list is empty, a message is printed and function exits.
o Calculations: Computes max_mark, min_mark, and average_mark.
o File Writing:
 Opens the specified filename in write mode.
 Writes the calculated maximum, minimum, and average to the file.
 Error Handling: Uses try-except to catch potential file system errors
 Prints a success or an error message.
2. Main:
o This block ensures the code inside is only executed when the script is run
directly.
o It prompts the user for the name of the output file.
o Calls the function to process the data.
Example:
Enter the name of the output file: results.txt
Enter a student's mark (or 'done' to finish): 85
Enter a student's mark (or 'done' to finish): 78.5
Enter a student's mark (or 'done' to finish): 92
Enter a student's mark (or 'done' to finish): 60
Enter a student's mark (or 'done' to finish): done
Results saved to 'results.txt' successfully.

Content of results.txt:
Maximum Mark: 92.0
Minimum Mark: 60.0
Average Mark: 78.88

``
``
6. Write program to save three students' names with their grades in mid-exam in text file
the name of text file is "mid_python.txt" They are (Yazan, 28), (Laila, 25), (Ahmad, 20)
calculate and print the average for the mid exam.
Input Example:

CODE:

``
LIST
• In Python, a list is a built-in data structure that allows you to store multiple items in a
single variable.
• Ordered: Items are stored in a specific order, and that order is preserved.
• Mutable: You can modify the items in a list (e.g., add, remove, or change items).
‫يمكن تعديل عناصرها‬
• Heterogeneous: They can store items of different data types (e.g., integers, strings, or
other lists).A list can be empty
‫يمكن ان تحتوي على انواع مختلفة من البيانات‬
• A collection allows us to put many values in a single “variable”
• A collection is nice because we can carry all many values around in one convenient
package.

Syntax
To create a list, use square brackets []:
my_list = [1, 2, 3, 4, 5]
Examples of Common Operations
1. Creating Lists ‫طريقة االنشاء‬
empty_list = []
numbers = [1, 2, 3, 4]
mixed_list = [1, "hello", 3.14, True]
nested_list = [1, [2, 3], 4]
2. Accessing Elements ‫الوصل الى عنصر في القائمة‬
Use indices (starting from 0): ‫تبدأ القائمة من العنصر رقم صفر‬
numbers = [10, 20, 30, 40]

``
print(numbers[0]) # Output: 10
print(numbers[-1]) # Output: 40 (last element)
3. Modifying Elements ‫تعديل اي عنصر باستخدام موقع العنثر داخل القائمة‬
numbers[1] = 25
print(numbers) # Output: [10, 25, 30, 40]
4. Adding Elements ‫إضافة عنصر جديد الى القائمة ويتم اضافته تلقائيا في‬
‫النهاية‬
 Append to the end:
numbers.append(50)
print(numbers) # Output: [10, 25, 30, 40, 50]
 Insert at a specific position
‫إضافة عنصر في موقع محدد‬
numbers.insert(1, 15)
print(numbers) # Output: [10, 15, 25, 30, 40, 50]
5. Removing Elements
 By value: ‫حذف عنصر من باستخدام القيمة‬
numbers.remove(25)
print(numbers) # Output: [10, 15, 30, 40, 50]
 By index:‫حذف عنصر باستخدام الموقع‬
numbers.pop(2)
print(numbers) # Output: [10, 15, 40, 50]
 Clear all elements: ‫حذف جميع العناصر‬
numbers.clear()
print(numbers) # Output: []
6. Iterating Through Lists
loop‫التعامل مع القائمة باستخدام ال‬
for num in [10, 20, 30]:
print(num)

``
#output [10,20,30]

OUTPUT
my_list1 = list((1, 2, 3)) [1, 2, 3]
print(my_list1)
my_list2 = [1, 2, 3] [1, 2, 3]
print(my_list2)
my_list3 = [1.0, 'Jessa', 3] [1.0, 'Jessa', 3]
print(my_list3)
my_list4 = list() []
print(my_list4)
my_list = [1, 2, 3] 3 ‫عدد عناصر‬
print(len(my_list)) list
my_list = [10, 20, 'Jessa', 12.50, 'Emma'] 20
print(my_list[1]) 'Emma'
print(my_list[4])
my_list = [10, 20, 'Jessa', 12.50, 'Emma'] 'Emma' ‫] تعني اخر‬1-[
# accessing last element of the list 12.5 list ‫عنصر في‬
print(my_list[-1]) ‫العنصر االخير‬ 20
# output 'Emma'

# accessing second last element of the list


print(my_list[-2])
# output 12.5 ‫العنصر الثاني من النهاية‬

# accessing 4th element from last


print(my_list[-4])
# output 20 ‫العنصر الرابع من النهاية‬
List Slicing
my_list = [10, 20, 'Jessa', 12.50, 'Emma', 25, 50] ['Jessa', 12.5, 'Emma'] ‫من العنصر‬
# Extracting a portion of the list from 2nd till ‫الثاني الى‬
#5th element ‫العنصر‬
print(my_list[2:5]) ‫الخامس‬

my_list = [5, 8, 'Tom', 7.50, 'Emma'] [5, 8, 'Tom', 7.5] ‫من البداية الى‬
# slice first four items ‫العنصر الرابع‬
print(my_list[:4])
my_list = [5, 8, 'Tom', 7.50, 'Emma'] [5, 'Tom', 'Emma'] ‫من البدايه الى‬
# print every second element ‫النهاية مع‬
‫اهمال اعنصر‬

``
# with a skip count 2 ‫ في كل‬2 ‫رقم‬
print(my_list[::2]) ‫مره ودوره‬
‫جديده‬

``
my_list = [5, 8, 'Tom', 7.50, 'Emma'] ['Emma', 7.5, 'Tom', 8, 5] ‫عكس‬
# reversing the list list ‫عناصر‬
print(my_list[::-1])
my_list = [5, 8, 'Tom', 7.50, 'Emma'] [7.5, 'Emma'] ‫من العنصر‬
# Without end_value ‫الثالث الى‬
# Stating from 3nd item to last item ‫النهاية‬
print(my_list[3:])
Iterating a List
my_list = [5, 8, 'Tom', 7.50, 'Emma'] 5
iterate a list # 8
:for item in my_list Tom
print(item) 7.5
Emma

my_list = [5, 8, 'Tom', 7.50, 'Emma'] 5


iterate a list # 8
:for i in range(0, len(my_list)) Tom
print each item using index number # 7.5
print(my_list[i]) Emma
my_list = list([5, 8, 'Tom', 7.50]) Tom', 7.5, ' ,8 ,5 [
]''Emma
)(Using append #
my_list.append('Emma')
print(my_list)
my_list = list([5, 8, 'Tom', 7.50]) Tom', 7.5, ' ,8 ,5 [
]'Emma', [25, 50, 75]
)(Using append #
my_list.append('Emma')
append the nested list at the end #
my_list.append([25, 50, 75])
print(my_list)
my_list = list([5, 8, 'Tom', 7.50]) ]Tom', 7.5 ' ,25 ,8 ,5 [ ‫إضافة‬
)(Using insert # 25 ‫العنصر‬
insert 25 at position 2 # ‫الى الموقع‬
my_list.insert(2, 25) ‫الثاني‬
print(my_list)

my_list = list([5, 8, 'Tom', 7.50])

)(Using insert #
insert 25 at position 2 #
my_list.insert(2, 25)
print(my_list)

``
Output [5, 8, 25, 'Tom', 7.5] #

insert nested list at at position 3 #


my_list.insert(3, [25, 50, 75])
print(my_list)
Output [5, 8, 25, [25, 50, 75], 'Tom', 7.5] #
my_list = list([2, 4, 6, 8, 10, 12]) ]12 ,10 ,8 ,6 ,4 ,20 [
,10 ,80 ,60 ,40 ,20 [
modify single item # ‫تعديل عنصر واحد‬ ]12
my_list[0] = 20 ,100 ,80 ,60 ,40 ,20 [
print(my_list) ]120
Output [20, 4, 6, 8, 10, 12] #

modify range of items # ‫تعديل مجموعة عناصر‬


modify from 1st index to 4th #
‫تبديل كل العناصر من الموقع االول الى‬
‫الثالث‬
my_list[1:4] = [40, 60, 80]
print(my_list)
Output [20, 40, 60, 80, 10, 12] #

modify from 3rd index to end #


my_list[3:] = [80, 100, 120]
print(my_list)
Output [20, 40, 60, 80, 100, 120] #
my_list = list([2, 4, 6, 8]) ]64 ,36 ,16 ,4 [ ‫ضرب كل‬
‫عنصر‬
change value of all items # ‫بنفسه‬
:for i in range(len(my_list)) )‫(تربيع العدد‬
calculate square of each number #
square = my_list[i] * my_list[i]
my_list[i] = square

print(my_list)
Output [4, 16, 36, 64] #
my_list = list([2, 4, 6, 8, 10, 12]) ]12 ,10 ,4 ,2 [

remove item 6 #
my_list.remove(6)
remove item 8 #
my_list.remove(8)

print(my_list)
Output [2, 4, 10, 12] #

``
my_list = list([6, 4, 6, 6, 8, 12]) ]12 ,8 ,4 [ ‫حذف كل‬
‫العناصر التي‬
:for item in my_list ‫قمينها‬
my_list.remove(6) 6 ‫تساوي‬

print(my_list)
Output [4, 8, 12] #
my_list = list([2, 4, 6, 8, 10, 12]) ]12 ,4 ,2 [

remove range of items #


remove item from index 2 to 5 #
del my_list[2:5]
print(my_list)
Output [2, 4, 12] #
remove all items starting from index 3 # ]6 ,4 ,2 [
my_list = list([2, 4, 6, 8, 10, 12])
del my_list[3:]
print(my_list)
Output [2, 4, 6] #
my_list = list([2, 4, 6, 8, 10, 12]) ][ ‫حذف كل‬
‫العناصر‬
clear list #
)(my_list.clear
print(my_list)
][ Output #
my_list = list([2, 4, 6, 8, 10, 12]) 3 Index
‫اي موقع‬
print(my_list.index(8)) ‫العنصر‬
Output 3 # list ‫داخل‬
my_list1 = [1, 2, 3] ]6 ,5 ,4 ,3 ,2 ,1 [
my_list2 = [4, 5, 6]

Using + operator #
my_list3 = my_list1 + my_list2
print(my_list3)
my_list1 = [1, 2, 3] ]1,2,3 [

Using = operator #
new_list = my_list1
printing the new list #
print(new_list)
Output [1, 2, 3] #

``
my_list1 = [1, 2, 3] ]66 ,3 ,2 ,1 [
making changes in the original list #
my_list1.append(66)
print(my_list1)
mylist = [3,2,1] ]3 ,2 ,1 [ ‫ترتيب‬
)(mylist.sort ‫عناصر‬
print(mylist)
mylist = [3, 4, 5, 6, 1] ]3 ,4 ,5 ,6 ,1 [ ‫عكس‬
)(mylist.reverse ‫العناصر‬
print(mylist)
mylist = [3, 4, 5, 6, 1] 6
print(max(mylist)) #returns the maximum 1
.number in the list
print(min(mylist)) #returns the minimum
.number in the list
mylist = [3, 4, 5, 6, 1] 19 ‫مجموع‬
print(sum(mylist)) ‫العناصر‬
creating even list for a range of numbers # ]8 ,6 ,4 ,2 ,0 [ list ‫انشاء‬
][ = squarelist1 ‫للعناصر‬
:for s in range(10) ‫الزوجية‬
:if s%2 == 0 ‫من صفر‬
squarelist1.append(s) ‫الى تسعة‬

print(squarelist1)
creating even square list for a range of # ]64 ,36 ,16 ,4 ,0 [ list ‫انشاء‬
numbers ‫لتربيع‬
][ = squarelist1 ‫العناصر‬
:for s in range(10) ‫من صفر‬
:if s%2 == 0 ‫الى تسعه‬
squarelist1.append(s ** 2)

print(squarelist1)

mylist = [3, 4, 5, 6, 1] ]6 ,5 ,4 ,3 ,1 [ ‫ترتيب‬


sorted_asc = sorted(mylist) ‫تنازلي‬
mylist = [3, 4, 5, 6, 1] ]1 ,3 ,4 ,5 ,6 [ ‫ترتيب‬
sorted_desc = sorted(mylist, reverse=True) ‫تصاعدي‬
print(sorted_desc)

``
Operation Description

x in l1 Check if the list l1 contains item x.

x not in l2 Check if list l1 does not contain item x.

Concatenate the lists l1 and l2. Creates a new list containing


l1 + l2
the items from l1 and l2.

l1 * 5 Repeat the list l1 5 times.

l1[i] Get the item at index i. Example l1[2] is 30.

List slicing. Get the items from index i up to


l1[i:j]
index j (excluding j) as a List. An example l1[0:2] is [10, 20]

List slicing with step. Returns a List with the items from
l1[i:j:k] index i up to index j taking every k-th item. An
example l1[0:4:2] is [10, 30].

len(l1) Returns a count of total items in a list.

Returns the number of times a particular item (60) appears in


l2.count(60)
a list. The answer is 2.

Returns the index number of a particular item (30) in a list.


l1.index(30)
The answer is 2.

Returns the index number of a particular item (30) in a list.


l1.index(30, 2, 5) But search Returns the item with maximum value from a list.
The answer is 60 only from index number 2 to 5.

``
Operation Description

Returns the item with a minimum value from a list. The


min(l1)
answer is 10.

Returns the item with maximum value from a list. The answer
max(l1)
is 60.

l1.append(100) Add item at the end of the list

l1.append([2, 5, 7]) Append the nested list at the end

l1[2] = 40 Modify the item present at index 2

l1.remove(40) Removes the first occurrence of item 40 from the list.

l1.clear() Make list empty

``
Multiple Choices
1. What is a characteristic of a list in Python?
a. Lists cannot be modified after creation.

b. Lists are surrounded by parentheses.

c. Lists are mutable and can store elements of different types. Answer: c

d. Lists are immutable.

2. What will the following code print?


my_list = [1, 2, 3]
print(my_list[1])
a. 1
b. 2 Answer: b
c. 3
d. IndexError

3. Which of the following methods is used to add an element to a list in Python?


a. insert()
b. append()
c. extend()
d. All of the above Answer: d
4. What is the result of the following code?
nums = [3, 41, 12, 9, 74, 15]
print(sum(nums) / len(nums))
a. 25.6 Answer: A
b. 154
c. 6
d. Error

``
5. Which of the following commands will create a list?
a. list1 = list()
b. list1 = []
c. list1 = list([1, 2, 3])
d. all of the mentioned Answer: d
6. What is the output when we execute list(“hello”)?
a. [‘h’, ‘e’, ‘l’, ‘l’, ‘o’] Answer: a
b. [‘hello’]
c. [‘llo’]
d. [‘olleh’]
7. Suppose list1 is [4, 2, 2, 4, 5, 2, 1, 0], Which of the following is correct syntax for slicing
operation?
a. print(list1[2:])
b. print(list1[:2])
c. print(list1[:-2])
d. all of the mentioned answer: d
8. Suppose list1 is [2, 33, 222, 14, 25], What is list1[-1]?
a. Error
b. None
c. 25 answer: c
d. 2
9. Suppose list1 is [2, 33, 222, 14, 25], What is list1[:-1]?
a. [2, 33, 222, 14] answer: a
b. Error
c. 25
d. [25, 14, 222, 33, 2]

True or False
a. A list in Python can contain elements of different data types.
Answer: True
b. Strings in Python are mutable, just like lists.
Answer: False
c. The split() function breaks a string into a list of words.
Answer: True
d. The len() function can be used on both lists and strings.
Answer: True

``
Coding
1. Basic List Operations
Write a Python program to create a list from user input and perform the following:
o Add items to the list using the append() method until the user types "stop".
o Print the list, its length, and the sum of numeric elements (if any).
my_list = []

while True:

item = input("Enter an item (or 'stop' to end): ")

if item.lower() == 'stop':

break

my_list.append(item)

sum =0

for x in my_list:

sum = sum + int(x)

print("Your list:", my_list)

print("Length of list:", len(my_list))

print("Sum = ", sum)

2. List Sorting
Write a Python program that:
a. Prompts the user to enter items into a list until they type "stop".
b. Creates two new lists: one sorted in ascending order and the other in descending
order.
c. Displays both sorted lists.
my_list = []

while True:

item = input("Enter an item (or 'stop' to end): ")

if item.lower() == 'stop':

break

``
my_list.append(item)

sorted_asc = sorted(my_list)

sorted_desc = sorted(my_list, reverse=True)

print("Ascending Order:", sorted_asc)

print("Descending Order:", sorted_desc)

3. Splitting Strings into Lists


Given the string "first;second;third", split it into a list using split() and print each element
individually.
line = "first;second;third"

items = line.split(";")

for item in items:

print(item)

4. Write python code that find all pairs that add up to a target sum.
def find_pairs(lst, target):

pairs = []

for i in range(len(lst)):

for j in range(i + 1, len(lst)):

if lst[i] + lst[j] == target:

pairs.append((lst[i], lst[j]))

return pairs

numbers = [2, 4, 3, 5, 7, 8]

target_sum = 10

print(find_pairs(numbers, target_sum))

# Output: [(2, 8), (3, 7)]

``
5. Write python code that rotate a list by n positions.
def rotate_list(lst, n):

n = n % len(lst) # Handle rotations greater than list length

return lst[-n:] + lst[:-n]

print(rotate_list([1, 2, 3, 4, 5], 2))

6. Write python code that check if a list is a palindrome.


def is_palindrome(lst):

return lst == lst[::-1]

print(is_palindrome([1, 2, 3, 2, 1]))

7. Write python code that remove duplicates and sort a list.


numbers = [2, 4, 3, 5, 3, 8, 5]

new_list = []

for x in numbers:

if x not in new_list:

new_list.append(x)

print(new_list)

8. Write python code that replace all even numbers in a list with 0.
numbers = [2, 4, 3, 5, 3, 8, 5, 10 , 9,12]

i=0

for x in numbers:

if x %2 == 0:

numbers[i] =0

i+=1

print(numbers)

``
9.Write a python program that uses a list to store student marks and calculates their sum, maximum,
minimum, and average.

Input:

Enter the number of students: 5

Enter the marks for each student:

85

90

78

92

88

ANSWER:

# Input: List of student marks

marks = []

n = int(input("Enter the number of students: "))

print("Enter the marks for each student:")

for i in range(n):

mark = int(input()) # Take input for each mark

marks.append(mark)

# Initialize variables

total = 0

maximum = marks[0]

minimum = marks[0]

``
# Calculate sum, max, and min

for mark in marks:

total += mark # Add mark to total

if mark > maximum:

maximum = mark # Update maximum

if mark < minimum:

minimum = mark # Update minimum

# Calculate average

average = total / n

# Output the results

print("\nStudent Marks Summary:")

print(f"Marks: {marks}")

print(f"Sum of marks: {total}")

print(f"Maximum mark: {maximum}")

print(f"Minimum mark: {minimum}")

print(f"Average mark: {average:.2f}")

``

You might also like