1- Write a python program that:
● Create a list of integer
● Print the first, third, and last element
● Change the second element of a list
● extract a sublist of last five elements.
2- Write a python program
● Take two list of integer a sinput.
● Merge both list into one list
● Sort the merged list in ascending order
● Remove all odd number from the sorted list
● Print final list.
3- Write a python program that:
● Create a list of string sized 10 elements
● Append "Delhi" to given list
● Insert "Newyork" at index 5
● Remove and return the second element
● Check if "mumbai" exists in list
● Count how many times delhi appears in
4- Generate squares of numbers 1 to 10 using list comprehension.
5- Write a python program that:
● Create a tuple of 10 elements
● Try modifying the second element of (1, 2, 3) and observe the error.
● Extract (3rd to 6th element) from given tuple
● Join (1, 2) and (3, 4) into a single tuple.
6- Compare memory usage of tuple(range(100)) vs list(range(100)) using [Link]().
7- Write a python program that:
9- Write a python program that:
● Create a new file [Link] and write "Hello, World!" to it.
● Read and print the contents of [Link] in one go.
● Add "This is a new line." to [Link] without overwriting.
● Print each line of [Link] using a loop.
● Verify if [Link] exists using [Link]().
10- Write a python program that:
● Create a new file [Link] and write "Essay" to it.
● Print only the 3rd line of a multi-line file.
● Count the total lines and words in [Link].
● Read a CSV file [Link] and print each row as a list.
9- import os
# 1. Create a new file [Link] and write "Hello, World!" to it
with open('[Link]', 'w') as file:
[Link]("Hello, World!\n")
# 2. Read and print the contents of [Link] in one go
print("\nReading entire file at once:")
with open('[Link]', 'r') as file:
content = [Link]()
print(content)
# 3. Add "This is a new line." to [Link] without overwriting
with open('[Link]', 'a') as file:
[Link]("This is a new line.\n")
# 4. Print each line of [Link] using a loop
print("\nReading file line by line:")
with open('[Link]', 'r') as file:
for line in file:
print(line, end='') # end='' to avoid double newlines
# 5. Verify if [Link] exists using [Link]()
print("\n\nFile existence check:")
if [Link]('[Link]'):
print("[Link] exists!")
else:
print("[Link] does not exist!")
Explanation of each step:
1. Creating and Writing to a File
○ We use open() with mode 'w' (write) to create the file
○ The with statement ensures proper file closure
○ We write the string "Hello, World!" followed by a newline
2. Reading Entire File
○ Open with mode 'r' (read)
○ [Link]() reads the entire content at once
○ We print the content which shows "Hello, World!"
3. Appending to File
○ Open with mode 'a' (append)
○ The new text is added without overwriting existing content
○ We add another newline for proper formatting
4. Reading Line by Line
○ The file object is iterable line-by-line
○ We print each line with end='' to avoid double newlines
○ Now shows both lines we've written
5. File Existence Check
○ [Link]() returns True if the file exists
○ We print confirmation that the file exists
o/p
Reading entire file at once:
Hello, World!
Reading file line by line:
Hello, World!
This is a new line.
File existence check:
[Link] exists!
10- import os
import csv
# Task 1: Create a new file [Link] and write "Essay" to it
with open('[Link]', 'w') as file:
[Link]("""Essay
Writing is an important skill.
The third line is here.
Python makes file operations easy.
Count lines and words.""")
# Task 2: Print only the 3rd line of a multi-line file
print("\nThird line of [Link]:")
with open('[Link]', 'r') as file:
lines = [Link]()
if len(lines) >= 3:
print(lines[2].strip()) # Index 2 is the 3rd line (0-based index)
else:
print("File doesn't have 3 lines")
# Task 3: Count the total lines and words in [Link]
print("\nCounting lines and words:")
with open('[Link]', 'r') as file:
content = [Link]()
line_count = len([Link]())
word_count = len([Link]())
print(f"Total lines: {line_count}")
print(f"Total words: {word_count}")
# Task 4: Read a CSV file [Link] and print each row as a list
print("\nReading [Link]:")
# First create the CSV file if it doesn't exist
if not [Link]('[Link]'):
with open('[Link]', 'w', newline='') as csvfile:
writer = [Link](csvfile)
[Link](['Name', 'Subject', 'Grade'])
[Link](['Alice', 'Math', 'A'])
[Link](['Bob', 'Science', 'B'])
[Link](['Charlie', 'History', 'C'])
# Now read and print the CSV
with open('[Link]', 'r') as csvfile:
reader = [Link](csvfile)
for row in reader:
print(row)
Explanation:
1. Creating [Link]:
○ We create a new file and write multiple lines about essays
○ The content spans 5 lines for demonstration
2. Printing the 3rd line:
○ We read all lines into a list using readlines()
○ Access index 2 (3rd line) and print it after stripping whitespace
○ Includes error handling if file has fewer than 3 lines
3. Counting lines and words:
○ splitlines() gives us all lines for counting
○ split() breaks content into words (by whitespace)
○ We print both counts
4. Reading [Link]:
○ First checks if CSV exists, creates it with sample data if not
○ Uses Python's csv module to properly handle CSV formatting
○ Prints each row as a list (including header row)
o/p
Third line of [Link]:
The third line is here.
Counting lines and words:
Total lines: 5
Total words: 19
Reading [Link]:
['Name', 'Subject', 'Grade']
['Alice', 'Math', 'A']
['Bob', 'Science', 'B']
['Charlie', 'History', 'C']