programming with python - rahul
programming with python - rahul
ON
PROGRAMMING WITH PYTHON
SESSION: 2024-2025
1
2
INDEX
Sr.No. TOPICS Pg.No.
3. Write a python program to get the largest number from a list. 9-11
4. Write a python program to get the smallest number from a list. 12-14
5. Write a python program to count the number of strings where the string length 15-17
is 2 or more and the first and last character are same from a given list of strings.
Sample list:[‘abe’, ‘xyz’, ‘aba’, ‘1221’]
6. Write a python program to get a list, sorted in increasing order by the last 18-20
element in each tuple from a given list of non-empty tuples. Sample list: [(2,5),
(1,2), (4,4), (2,3), (2,1)] Expected result: [(2,1),(1,2),(2,3),(4,4),(2,5)]
10. Write a python program to find the list of words that are longer than n from a 32-35
given list of words.
3
1. WRITE A PYTHON PROGRAM TO SUM ALL THE ITEMS IN A LIST
# Example usage
my_list = [1, 2, 3, 4, 5]
# Using Method 1
result1 = sum_list1(my_list)
print("Sum using sum() function:", result1)
# Using Method 2
result2 = sum_list2(my_list)
print("Sum using for loop:", result2)
When you run this program with the example list [1, 2, 3, 4, 5],
Both methods will give you the same result. The sum() function is generally preferred as it's more
concise and built into Python, but the loop method shows how you could do it manually if needed.
4
OUTPUT:
5
2. WRITE A PYTHON PROGRAM TO MULTIPLY ALL THE ITEMS IN A
LIST
def multiply_list2(numbers):
return prod(numbers)
# Example usage
my_list = [1, 2, 3, 4, 5]
# Using Method 1
result1 = multiply_list1(my_list)
print("Product using for loop:", result1)
# Using Method 2
result2 = multiply_list2(my_list)
print("Product using math.prod():", result2)
When you run this program with the example list [1, 2, 3, 4, 5],
Key points:
6
We start with 1 (not 0) because multiplying by 0 would always give 0
math.prod() is simpler but requires Python 3.8 or later
The for loop method works in all Python versions
You can modify my_list to contain any numbers you want to multiply. The program assumes the
list contains numbers (integers or floats).
7
OUTPUT:
8
3. WRITE THE PYTHON PROGRAM TO GET THE LARGEST NUMBER
FROM A LIST
# Example usage
my_list = [4, 2, 7, 1, 9, 5]
# Using Method 1
result1 = find_largest1(my_list)
print("Largest using max() function:", result1)
# Using Method 2
result2 = find_largest2(my_list)
print("Largest using for loop:", result2)
This program provides two ways to find the largest number in a list:
When you run this program with the example list [4, 2, 7, 1, 9, 5],
Both methods will give you the same result. The max() function is generally preferred as it's more
concise and optimized, but the loop method shows how you could do it manually.
9
Notes:
10
OUTPUT:
11
4. WRITE THE PYTHON PROGRAM TO GET THE SMALLEST NUMBER
FROM A LIST
return smallest
12
1. Using Python's built-in min() function (simplest approach)
2. Using a loop to manually compare numbers (shows the logic)
Key features:
13
OUTPUT:
14
5. WRITE A PYTHON PROGRAM TO COUNT THE NUMBER OF
STRINGS WHERE THE STRING LENGTH IS 2 OR MORE AND THE
FIRST AND LAST CHARACTER ARE SOME FROM A GIVEN LIST OF
STRINGS. SAMPLE LIST:['abe', 'xyz', 'aba', '1221']
def count_matching_strings(string_list):
# Initialize counter
count = 0
return count
This program:
15
1. Defines a function count_matching_strings that takes a list of strings as input
2. Uses a counter variable to keep track of matching strings
3. Checks two conditions for each string:
o Length is 2 or more (len(string) >= 2)
o First character equals last character (string[0] == string[-1])
4. Returns the total count of matching strings
16
OUTPUT:
17
6. WRITE A PYTHON PROGRAM TO GET A LIST, SORTED IN
INCREASING ORDER BY THE LAST ELEMENT IN EACH TUPLE FROM
A GIVEN LIST OF NON-EMPTY TUPLES. SAMPLE LIST:
[(2,5),(1,2),(4,4),(2,3),(2,1)] EXPECTED RESULT: [(2,1),(1,2),(2,3),(4,4),(2,5)]
def sort_by_last_element(tuple_list):
# Sort using sorted() with a key function that returns the last element
return sorted(tuple_list, key=lambda x: x[-1])
This program:
How it works with the sample list [(2,5), (1,2), (4,4), (2,3), (2,1)]:
18
Alternative implementation using the sort() method:
def sort_by_last_element_alt(tuple_list):
result = tuple_list.copy()
result.sort(key=lambda x: x[-1])
return result
# Test it
Key features:
Works with tuples of any length (as long as they're not empty)
Handles empty lists
Preserves the original tuple structure
Maintains stable sorting (if two tuples have the same last element, their original order is
preserved)
The sorted() version creates a new list, while the sort() version modifies a copy
19
OUTPUT:
20
7. WRITE A PYTHON PROGRAM TO REMOVE DUPLICATES FROM A
LIST
21
empty_list = []
single_item = [1]
1. Set Method:
o Fastest and most concise
o Doesn't preserve original order
o Works with any hashable elements
2. List Comprehension Method:
o Preserves original order
o More readable than complex loops
o Uses extra memory for the 'seen' list
3. Loop Method:
o Preserves original order
o Most explicit and easy to understand
o Good for modification or adding conditions
Important notes:
The set method might not preserve the original order (depends on Python version)
All methods work with lists containing different data types (integers, strings, floats, etc.)
For unhashable elements (like lists or dictionaries), use the loop or list comprehension
method
All methods handle empty lists and single-item lists correctly
22
OUTPUT:
23
8. WRITE A PYTHON PROGRAM TO CHECK A LIST IS EMPTY OR NOT
24
print("\nAdditional tests:")
print("Single item:", is_empty_truthy(single_item))
print("Nested empty list:", is_empty_truthy(nested_empty))
print("String list:", is_empty_truthy(string_list))
1. len() Method:
o Explicit and clear
o Easy to understand
o Returns True if length is 0
2. Comparison Method:
o Straightforward comparison
o Very readable
o Compares directly with empty list
3. Truthiness Method:
o Most pythonic approach
o Shortest and cleanest
o Empty lists are "falsy" in Python
Key points:
def check_list_empty():
# Get list from user
user_input = input("Enter elements separated by spaces (or press enter for empty): ")
user_list = user_input.split() if user_input else []
# Check if empty
if not user_list:
print("The list is empty")
25
else:
print("The list is not empty, it contains:", user_list)
26
OUTPUT:
27
9. WRITE A PYTHON PROGRAM TO CLONE OR COPY A LIST
clone1 = clone_list_constructor(original)
clone2 = clone_list_copy(original)
clone3 = clone_list_slice(original)
clone4 = clone_list_comprehension(original)
28
print("Clone (comprehension):", clone4)
1. list() Constructor:
o Simple and readable
o Creates a new list from any iterable
2. copy() Method:
o Explicit method for copying
o Available since Python 3.3
29
3. Slice Operator:
o Traditional Python idiom
o Very concise
4. List Comprehension:
o Flexible (can modify elements during copy)
o More verbose but clear
Important notes:
def demonstrate_copy():
original = [1, 2, ["a", "b"]]
clone = clone_list_copy(original)
# Modify original
original[0] = 99
original[2][0] = "z"
30
OUTPUT:
31
10. WRITE A PYTHON PROGRAM TO FIND THE LIST OF WORDS THAT
ARE LONGER THAN N FROM A GIVEN LIST OF WORDS
32
test_list3 = ["python", "java", "c"]
print("\nAdditional tests:")
print("Test 1 (n=2):", find_longer_words_comp(test_list1, 2))
print("Test 2 (n=5):", find_longer_words_comp(test_list2, 5))
print("Test 3 (n=4):", find_longer_words_comp(test_list3, 4))
1. Loop Method:
o Explicit and easy to understand
o Builds result list incrementally
2. List Comprehension Method:
o Concise and pythonic
o Single-line solution
3. Filter Method:
o Functional programming style
o Uses lambda function for condition
For the sample list ["cat", "elephant", "dog", "hippopotamus", "rat", "kangaroo"] with n = 3:
Key features:
def get_longer_words_user():
33
# Get input from user
words = input("Enter words separated by spaces: ").split()
try:
34
OUTPUT
35